<?php

namespace App\Http\Controllers\Fpdx;

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

class KdListen extends Listen
{
    /**
     * KdListen constructor.
     */
    public function __construct()
    {
        parent::__construct('koudai');
    }

    /**
     * @return array
     * @throws \ApiException
     */
    public function open()
    {
        $this->initMedia($this->media_id);
        return [
            'errcode' => 0,
            'errmsg' => '成功'
        ];
    }

    /**
     * 初始化公众号
     * @param  string media_id 公众号id
     * @return boolean
     * @throws \ApiException
     */
    public function initMedia(string $media_id)
    {
        MediaKeyModel::updateOrCreate([
            'media_id' => $media_id,
            'app' => 'fpdx',
            'plat' => 'koudai'
        ], ['keywords' => json_encode(["分配对象"])]);
        return $this->syncMedia($media_id);
    }

    /**
     * 同步公众号信息
     * @param  string media_id 公众号id
     * @return boolean
     * @throws \ApiException
     */
    public function syncMedia(string $media_id)
    {
        $data = $this->getMediaInfo($media_id);
        MediaModel::updateOrCreate(['media_id' => $media_id], [
            'public_name' => $data->nick_name,
            'school' => $data->school,
            'verify_type_info' => $data->verify_type_info
        ]);
        return true;
    }

    /**
     * 获取公众号id
     * @param  string  $media_id  公众号id
     * @return Exception
     * @throws \ApiException
     */
    public function getMediaInfo(string $media_id)
    {
        $url = config('fpdx.koudai.dns') . "/app/data/getMediaInfo";
        $data = [
            'media_id' => $media_id,
            'api_key' => config('fpdx.koudai.key'),
            'timestamp' => time(),
            'nonce_str' => bin2hex(\openssl_random_pseudo_bytes(16))
        ];
        $data['sign'] = $this->sign($data);
        $response = json_decode(\Curl::to($url)->withData($data)->post());
        if ($response->errcode == 0) {
            return $response->errmsg;
        } else {
            throw new \ApiException($response->errmsg, $response->errcode);
        }
    }
}
