<?php

/**
 * Class DefaultController
 * @author Blackbinbin
 */
class DefaultController extends BaseController {

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

    const SERVER_ID = 1; // 客服id

    /**
     * 判断ip，输出首页
     */
    public function actionIndex() {
//        if (ENV != ENV_DEV) {
//            header('Location: https://dice.eosget.io/#/box');
//            Response::exitMsg('');
//        } else {
//            // 清除无效的cookie
//            Account::checkToken();
//
//            if (ENV != ENV_DEV) {
//                $GLOBALS['eosProtocol'] = "https";
//                $GLOBALS['eosHost'] = "api.eosbeijing.one";
//                $GLOBALS['eosPort'] = 443;
//            }

            $this->tpl->display('index');
//        }
    }

    /**
     * 判断ip，输出首页
     */
    public function actionMini() {
        $this->tpl->display('mini');
    }

    /**
     * 判断ip，输出首页
     */
    public function actionSw() {
        // 不需要默认头部信息
        $GLOBALS['FORBID_ORIGIN'] = true;

        $path = BASE_DIR . 'dist/sw.js';

        // 增加浏览器缓存
        $filemd5 = md5_file($path);
        $this->_addEtag($filemd5);

        $content = file_get_contents($path);
        header("Content-Type: application/javascript; charset=utf-8");
        Response::exitMsg($content, CODE_SUCCESS, null, true);
    }

    private function _addEtag($etag) {
        // always send headers
        header("Etag: $etag");
        // exit if not modified
        if (@trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
            header("HTTP/1.1 304 Not Modified");
            Response::exitMsg('', CODE_SUCCESS, '304 Not Modified');
        }
    }

    /**
     * 分享跳转
     * @author solu
     * @param $args
     */
    public function actionShare($args) {
        $rules = [
            'group_name' => ['string', 'reg' => '/^[a-z0-9\.]+/i', 'desc' => '群名'],
        ];
        Param::checkParam2($rules, $args);

        $objGroup = new GroupInfo();
        $group = $objGroup->objTable->getRow(['group_name' => $args['group_name']], ['_field' => 'group_id, group_name, group_title']);
        $groupId = $group['group_id'] ?: GroupInfo::OFFICIAL_ID;

        $format = '%s/#/group/%s';
        if (is_mobile_request()) {
            $format = '%s/h5.html#/group/%s';
        }
        $url = sprintf($format, URL_SELF, $groupId);
        Response::exitMsg("<script>location.replace('{$url}')</script>");
    }

    /**
     * 申请群认证
     * @author solu
     * @param $args
     * @return array
     */
    public function actionGroupAuth($args) {
        $rules = [
            'group_id' => ['int', 'desc' => '群id'],
        ];
        Param::checkParam2($rules, $args);

        $userId = User::getUserId();
        if (!(new UserGroup())->isAdmin($args['group_id'], $userId)) {
            Response::error(CODE_NO_PERMITION);
        }

        $serverId = self::SERVER_ID; // 客服id
        $msg =<<<MSG
欢迎申请群组认证，您需要提供如下信息：
1. 项目地址（如：https://dice.eosget.io）
2. 代币合约名（如：eosio.token）
3. 代币名（如：EOS）
4. Vip合约名（如：eosgetadmin1）
5. Vip表名（如：vip）
6. 等级字段名（如：vip_level）
7. 投注额字段名（如：total_bet_amount)
MSG;

        $msg = Utils::encodeRC4($msg);
        $objSession = new Session();
        $sessionId = Session::getPersonSessionId($serverId, $userId);
        try {
            $objSession->sendPersonMsg($serverId, $sessionId, Session::MSG_TYPE_TEXT, $msg, true);
        } catch (Exception $e) {}

        return compact('serverId');
    }

    /**
     * 问题反馈
     * @author solu
     * @param $args
     * @return array
     */
    public function actionTick($args) {
        $rules = [];
        Param::checkParam2($rules, $args);

        $userId = User::getUserId();
        $serverId = self::SERVER_ID; // 客服id
        $msg =<<<MSG
Hi，请问您遇到了什么问题？
MSG;

        $msg = Utils::encodeRC4($msg);
        $objSession = new Session();
        $sessionId = Session::getPersonSessionId($serverId, $userId);
        try {
            $objSession->sendPersonMsg($serverId, $sessionId, Session::MSG_TYPE_TEXT, $msg, true);
        } catch (Exception $e) {}

        return compact('serverId');
    }
}

