<?php
/**
 * 对外接口
 * User: solu
 * Date: 2019/4/16
 * Time: 11:23 AM
 */

class ApiController extends BaseController {

    /**
     * 创建群
     * @author solu
     * @param $args
     * @return array
     */
    public function actionCreateGroup($args) {
        $rules = [
            'creator' => ['int', 'desc' => '创建者id'],
            'group_title' => ['string', 'desc' => '群标题'],

            'timestamp' => ['int', 'desc' => '时间戳（秒'],
            'sign' => ['string', 'desc' => '签名'],

        ];
        Param::checkParam2($rules, $args);
        $group_id = 0;
        try {
            $args = $this->_valid($args);

            $sess = (new GroupInfo())->create($args);
            $group_id = intval($sess['session_id']);
        } catch (Exception $e) {
            Response::error($e->getCode(), $e->getMessage());
        }

        return compact('group_id');
    }

    /**
     * 删除群
     * @author solu
     * @param $args
     */
    public function actionDiscardGroup($args) {
        $rules = [
            'creator' => ['int', 'desc' => '创建者id'],
            'group_id' => ['int', 'desc' => '群标id'],

            'timestamp' => ['int', 'desc' => '时间戳（秒'],
            'sign' => ['string', 'desc' => '签名'],

        ];
        Param::checkParam2($rules, $args);
        try {
            $args = $this->_valid($args);

            (new GroupInfo())->discard($args['creator'], $args['group_id']);
        } catch (Exception $e) {
            Response::error($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 校验参数
     * @author solu
     * @param $args
     * @return mixed
     * @throws Exception
     */
    private function _valid($args) {
        $creator = $args['creator'];
        if (!$creator) {
            throw new Exception("miss creator", CODE_PARAM_ERROR);
        }
        $apiToken = (new TableHelper('user_info', 'dw_chat'))->getOne(['user_id' => $creator], ['_field' => 'api_token']);
        if (!$apiToken) {
            throw new Exception('miss api token', CODE_NO_PERMITION);
        }

        $sign = arrayPop($args, 'sign');
        $mySign = $this->_sign($args, $apiToken);
        if ($sign !== $mySign) {
            throw new Exception('sign error', CODE_NO_PERMITION);
        }

        $timestamp = arrayPop($args, 'timestamp');
        if (time() - 60 > $timestamp) {
            throw new Exception('timeout', CODE_PARAM_ERROR);
        }

        return $args;
    }

    private function _sign($data, $token) {
        ksort($data);
        $param = http_build_query($data);
        $param = str_replace('%2A', '*', $param);

        $str = "token={$token}{$param}";
        return md5($str);
    }
}