<?php

namespace App\Http\Controllers\Wap\Subscribe;

use Illuminate\Http\Request;
use GuzzleHttp\Client;
use App\Http\Controllers\Wap\BaseController;
use Redis;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use Cookie;
use Hashids;
use Log;

class SubscribeController extends BaseController
{

    /**
     * @apiDefine Subscribe 强关
     */

    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取强关二维码
     * @api {get} subscribe/qrcode 获取强关二维码
     * @apiGroup Subscribe
     * @apiName getSubscribeQrcode
     * @apiParam   {int}         bid bid
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {String}      data.src 分页结果集
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data:{
     *           src:'sdfasdfas'
     *       }
     */
    public function getSubscribeQrcode(Request $request)
    {
        $bid = $request->input('bid', 0);
        if ($bid) {
            try {
                $bid = Hashids::decode($bid)[0];
            } catch (\Exception $e) {

            }

        }
        $bid = (int)$bid;
        $officialAccount = $this->getOfficialAccount();
        if ($officialAccount) {
            $info['appid'] = $officialAccount->appid;
            $src = $this->getRcodeInfo($info, $bid);
            if ($src) {
                return response()->success(['src' => $src,'head_img'=>$officialAccount->head_img]);
            }
        }
        return response()->success();

    }

    protected function getOfficialAccount()
    {
        $distribution_channel_id = $this->distribution_channel_id;
        $res = OfficialAccountService::canUseOfficialAccountByChannelId(compact('distribution_channel_id'));
        if (isset($res->nickname) && !empty($res->nickname)) {
            Cookie::queue('force_subscribe_name', $res->nickname, env('U_COOKIE_EXPIRE'));
        }
        return $res;
    }

    protected function getRcodeInfo($param, $bid)
    {
        $param_need = [
            'gzh_app_id' => $param['appid'],
            'scene_id' => $this->uid,
            'timestamp' => time(),
        ];
        $param_need['sign'] = $this->getSign($param_need);
        $client = new Client(['timeout' => 3.0,]);
        try {
            Log::info('ruo guan get qrcode url is:'.'https://zsyauth.aizhuishu.com/api/get_qrcode_url?'.http_build_query($param_need));
            $qrcode_url_res = $client->request('get', 'https://zsyauth.aizhuishu.com/api/get_qrcode_url?' . http_build_query($param_need))->getBody()->getContents();
            if ($qrcode_url_res) {
                $qrcode_url = json_decode($qrcode_url_res, true);
                if ($qrcode_url['code'] == 1) {
                    //保存强关时的bid
                    if (isset($qrcode_url['data']) && !empty($qrcode_url['data'])) {
                        Redis::hset('force_subscribe_from_bid', $param['appid'] . '_' . $this->uid, $bid);
                        $send_order_id = Cookie::get('send_order_id') ? Cookie::get('send_order_id') : 0;
                        Redis::hset('force_subscribe_from_send_order_id', $param['appid'] . '_' . $this->uid, $send_order_id);
                        Log::info('ruo guan uid is'.$this->uid.'--qrcode is:'.$qrcode_url['data']);
                        return $qrcode_url['data'];
                    }
                }
            }
        } catch (\Exception $e) {
            Redis::sadd('force_subscribe_qrcode:error', $param['appid'] . '_' . time());
        }

        return false;
    }

    //只获取用户的强关二维码
    protected function getSimpleRcodeInfo($appid)
    {
        $param_need = [
            'gzh_app_id' => $appid,
            'scene_id' => $this->uid,
            'timestamp' => time(),
        ];
        $param_need['sign'] = $this->getSign($param_need);
        $client = new Client(['timeout' => 3.0,]);
        try {
            $qrcode_url_res = $client->request('get', 'https://zsyauth.aizhuishu.com/api/get_qrcode_url?' . http_build_query($param_need))->getBody()->getContents();
            if ($qrcode_url_res) {
                $qrcode_url = json_decode($qrcode_url_res, true);
                if ($qrcode_url['code'] == 1) {
                    if (isset($qrcode_url['data']) && !empty($qrcode_url['data'])) {
                        return $qrcode_url['data'];
                    }
                }
            }
        } catch (\Exception $e) {

        }
        return false;
    }

    //获取用户的强关信息
    function getFromUser()
    {
        Cookie::queue('force_show_qrcode', 1, -1);
        $uid = $this->uid;
        $user_info = ForceSubscribeService::forceSubscribeUsersByUid(compact('uid'));
        if(isset($_GET['d']))
        {
        dump($user_info);
            }
        if($user_info)
        {
            $appid = $user_info->appid;
            $official_account = OfficialAccountService::officialAccountByAppid(compact('appid'));
            if(isset($_GET['d']))
            {
                dump($official_account);
            }
            $title = $official_account->nickname;
            $img = 'https://open.weixin.qq.com/qr/code?username='.$official_account->name;
            if(isset($_GET['d']))
            {
                $qrcode_url = $this->getSimpleRcodeInfo($appid);dump($qrcode_url);
            }
            if($qrcode_url = $this->getSimpleRcodeInfo($appid))//用服务号强关二维码
            {
                $img = $qrcode_url;
            }
        }else{
            return redirect()->to('/recent');
        }

        $head_img_pool = [
            'https://cdn-novel.iycdm.com/h5/subscribe/headimg/1.png',
            'https://cdn-novel.iycdm.com/h5/subscribe/headimg/2.png',
            'https://cdn-novel.iycdm.com/h5/subscribe/headimg/3.png'
        ];

        $head_img = array_random($head_img_pool);

        return view('wap.userSubInfo',compact('head_img','img','title'));
    }

}
