<?php

namespace App\Http\Controllers\Fpdx;

use App\Exceptions\AlertException;
use App\Models\Fpdx\MediaModel;
use App\Models\Fpdx\MediaKeyModel;

class WxListen extends Listen
{
    public function __construct()
    {
        parent::__construct('weixiao');
    }

    /**
     * @return array
     */
    public function open()
    {
        // $this->message = '{"media_id":"gh_560e659c5877","api_key":"C3D27FE833E23681","timestamp":1526029895,"nonce_str":"E284DDB7B89C82D6A1883AB712E3F41A","sign":"xxxx"}';
        $message = json_decode($this->message, true);
        $sign = $message['sign'];
        unset($message['sign']);
        if ($sign == $this->sign($message)) {
            $this->initMedia($message['media_id']);
            return [
                'errcode' => 0,
                'errmsg' => '',
                'token' => 'fpdx',
                'is_config' => 1
            ];
        } else {
            return [
                'errcode' => 5004,
                'errmsg' => '签名错误'
            ];
        }
    }

    /**
     * 初始化公众号
     * @param  string media_id 公众号id
     * @return boolean
     */
    public function initMedia(string $media_id)
    {
        MediaModel::firstOrCreate(['media_id' => $media_id]);
        MediaKeyModel::updateOrCreate([
            'media_id' => $media_id,
            'app' => 'fpdx',
            'plat' => 'weixiao'
        ], ['keywords' => json_encode(["分配对象"])]);
        return true;
    }

    /**
     * 同步公众号信息
     * @param  string media_id 公众号id
     * @return boolean
     * @throws AlertException
     */
    public function syncMedia(string $media_id)
    {
        $first = MediaModel::where('media_id', $media_id)->first();
        if (collect($first)->isEmpty()) {
            $data = $this->getMediaInfo($media_id);
            MediaModel::updateOrCreate(['media_id' => $media_id], [
                'public_name' => $data->name,
                'school' => $data->school_name,
                'verify_type_info' => isset($data->verify_type) ? $data->verify_type : -1
            ]);
        }
        return true;
    }

    /**
     * 获取公众号id
     * @param  string  $media_id  公众号id
     * @return object
     * @throws AlertException
     */
    public function getMediaInfo(string $media_id)
    {
        $url = config('fpdx.weixiao.dns') . "/apps/v1/data/media-info";
        $data = [
            'media_id' => $media_id,
            'api_key' => config('fpdx.weixiao.key'),
            'timestamp' => time(),
            'nonce_str' => bin2hex(\openssl_random_pseudo_bytes(16))
        ];
        $data['sign'] = $this->sign($data);
        $response = \Curl::to($url)->withData($data)->asJsonResponse(true)->post();
        if (isset($response->errcode) && $response->errcode == 0) {
            return $response;
        } else {
            throw new AlertException("网络繁忙", 500);
        }
    }
}
