<?php

namespace App\Http\Controllers\WapAlipay;
use Illuminate\Routing\Controller;

use Illuminate\Http\Request;
use Cookie;
use App\Modules\User\Services\UserService;
class BaseController extends Controller
{
    /**
     * 请求接口的地址前缀
     * @var mixed
     */
    protected $_url_prefix;


    /**
     * 用户id
     * @var int
     */
    protected $uid;

    /**
     * 公众号接口签名密钥
     * @var string
     */
    protected $secret_key = 'zhuishuyun#_2017';

    /**
     * 渠道id
     * @var
     */
    protected $distribution_channel_id;

    function __construct(Request $request)
    {
        $domain = _domain();
        $this->distribution_channel_id = str_replace('site','',explode('.',$domain)[0]);
        if(!is_numeric($this->distribution_channel_id)){
            $this->distribution_channel_id = decodeDistributionChannelId($this->distribution_channel_id);
        }
        $this->_url_prefix = env('PUBLIC_BASE_API');
        $user_cookie = Cookie::get(env('COOKIE_AUTH_WEB_WECHAT'));
        $this->uid = $user_cookie ? decrypt($user_cookie) : null;
        //$this->uid = 13;
    }

    protected function userInfo($uid){
        $user = UserService::getById($uid);
        return  $user;
    }

    protected function checkUid(){
        if(!$this->uid) return false;
        return true;
    }

    public function __get($name)
    {
        if($name == '_user_info'){
            return $this->userInfo($this->uid);
        }
        return null;
     }

    protected function joinUrl($url)
    {
        if (stripos($url, '/') === 0) {
            $url = substr($url, 1);
        }
        return $this->_url_prefix . $url;
    }


    /**
     * 公众号签名@华灯初上
     * @param $params
     * @return string
     */
    protected function getSign($params)
    {
        $url = $this->arr_to_url($params, false);
        $url = $url . '&key=' . $this->secret_key;

        $sign = md5($url);
        return $sign;
    }

    /**
     * 公众号签名@华灯初上
     * @param $array
     * @param bool $has_sign
     * @return string
     */
    protected function arr_to_url($array, $has_sign = false)
    {
        ksort($array);
        reset($array);
        $arg = "";
        while (list ($name, $val) = each($array)) {
            if ($name == 'sign' && !$has_sign) continue;
            if (strpos($name, "_") === 0)
                continue;
            if (is_array($val))
                $val = join(',', $val);
            if ($val === "")
                continue;
            $arg .= $name . "=" . $val . "&";
        }
        $arg = substr($arg, 0, count($arg) - 2);

        return $arg;
    }
}