<?php

namespace App\Services\QQMiniApp;

use App\Models\QQ\FormIdModel;
use App\Models\User\AuthKey;
use Ixudra\Curl\Facades\Curl;

class Template extends Base
{


    /**
     *
     * @var string
     */
    public const REQUEST_URL = "https://api.q.qq.com/api/json/template/send";


    /**
     * 通知的唯一字符
     * @var string
     */
    protected $uuid;


    /**
     * 通知标题
     * @var string
     */
    protected $title;


    /**
     * 接受者uid
     * @var int
     */
    protected $to_uid = 0;

    /**
     * 接收者（用户）的 openid
     * @var string
     */
    protected $openid;

    /**
     * 所需下发的模板消息的id
     * @var string
     */
    protected $template_id;

    /**
     * 点击模板卡片后的跳转页面，仅限本小程序内的页面。该字段不填则模板无跳转
     * @var string
     */
    protected $page = "pages/starter/starter";

    /**
     *
     * 模板内容，不填则下发空模板。
     * @var array
     */
    protected $parameters = array();

    /**
     * 模板需要放大的关键词，不填则默认无放大
     * @var null|string
     */
    protected $emphasis_keyword = null;


    /**
     * 错误码
     * @var int
     */
    protected $err_code = 0;

    /**
     * 错误信息
     * @var string
     */
    protected $err_msg;


    /**
     * 发送者
     * @param $to_user
     * @return $this
     */
    public function toUser($to_user)
    {
        if (is_int($to_user)) {
            $this->to_uid = $to_user;
            $this->openid = AuthKey::where('uid', $to_user)->where('auth_type', $this->app_id)->value('auth_key');
        } else {
            $this->openid = $to_user;
        }
        return $this;
    }


    /**
     * 设置唯一字符串
     * @param $uuid
     * @return $this
     */
    public function setUuid($uuid)
    {
        $this->uuid = $uuid ?: uuid();
        return $this;
    }


    public function getUuid()
    {
        return $this->uuid;
    }


    /**
     * 设置通知的标题
     * @param $title
     * @return $this
     */
    public function setTitle($title)
    {
        $this->title = $title;
        return $this;
    }


    public function getTitle()
    {
        return $this->title;
    }


    /**
     * 设置模版ID
     * @param $template_id
     * @return $this
     */
    public function setTemplateId($template_id)
    {
        $this->template_id = $template_id;
        return $this;
    }


    /**
     * 获取template_id
     * @return mixed
     */
    public function getTemplateId()
    {
        return $this->template_id;
    }


    /**
     * 设置参数
     * @param $data
     * @return $this
     */
    public function setParameters($data)
    {
        $this->parameters = $data;
        return $this;
    }


    /**
     * 获取参数
     * @return mixed
     */
    public function getParameters()
    {
        return $this->parameters;
    }


    /**
     * 设置page
     * @param $page
     * @return $this
     */
    public function setPage($page)
    {
        $this->page = $page;
        return $this;
    }


    /**
     * 获取page
     * @return mixed
     */
    public function getPagePath()
    {
        $path = urlencode("/" . $this->page);
        $page_path = "pages/starter/starter?log_type=notice&log_id={$this->uuid}&launch_type=free&url={$path}";
        return $page_path;
    }


    /**
     * 模板需要放大的关键词
     * @param $keyword
     * @return string|null
     */
    public function setEmphasis($keyword)
    {
        $this->emphasis_keyword = $keyword;
        return $this;
    }


    /**
     * 获取模板需要放大的关键词
     * @return string|null
     */
    public function getEmphasis()
    {
        return $this->emphasis_keyword;
    }


    /**
     * 获取form_id
     * @return mixed
     */
    protected function getFormId()
    {
        return FormIdModel::where('openid', $this->openid)
            ->where('appid', $this->app_id)
            ->where('created_at', '>', time() - 6 * 86400)
            ->where('send_at', 0)
            ->orderBy('id', 'asc')
            ->first();
    }


    /**
     * 获取通知的地址
     * @return string
     */
    protected function getRequestUrl()
    {
        $token = $this->getAccessToken();
        return self::REQUEST_URL . "?access_token=" . $token;
    }


    /**
     * 发送通知
     * @return $this
     */
    public function send()
    {
        $form = $this->getFormId();

        if (collect($form)->isEmpty()) {
            // 成功或失败code/msg
            $this->err_code = 41027;
            $this->err_msg = "form_id为空";
            $this->logger();
            return $this;
        }
        // 发起微信请求
        $response = Curl::to($this->getRequestUrl())
            ->withData([
                'touser' => $this->openid,
                'template_id' => $this->template_id,
                'page' => $this->getPagePath(),
                'form_id' => $form->form_id,
                'data' => $this->parameters,
                'emphasis_keyword' => $this->emphasis_keyword
            ])
            ->asJson()
            ->post();

        // 成功或失败code/msg
        $this->err_code = $response->errcode;
        $this->err_msg = $response->errmsg;

        // 核销表单
        $form->send_at = time();
        $form->errmsg = $this->err_msg;
        $form->save();

        $this->logger();

        return $this;
    }


    public function getContentString()
    {
        return $this->parameters
            ? json_encode($this->parameters, JSON_UNESCAPED_UNICODE)
            : '';
    }


    /**
     * 错误码
     * @return mixed
     */
    public function getCode()
    {
        return $this->err_code;
    }


    /**
     * 错误信息
     * @return string
     */
    public function getMessage()
    {
        return $this->err_msg;
    }


    public function logger()
    {
        if ($this->err_code == 0) {
            \DB::connection('mysql_datalog')
                ->table("notice_logs")
                ->insert([
                    'uid' => $this->to_uid,
                    'openid' => $this->openid,
                    'title' => $this->title,
                    'notice_type' => "QQ小程序模板消息",
                    'content' => $this->getContentString(),
                    'template_id' => $this->template_id,
                    'page' => $this->page,
                    'uuid' => $this->uuid,
                    'result' => true,
                    'created_at' => time(),
                    'date' => date('Y-m-d')
                ]);
        } else {
            \DB::connection('mysql_datalog')
                ->table("notice_logs")
                ->insert([
                    'uid' => $this->to_uid,
                    'openid' => $this->openid ?: '',
                    'title' => $this->title,
                    'notice_type' => "QQ小程序模板消息",
                    'content' => $this->getContentString(),
                    'template_id' => $this->template_id,
                    'page' => $this->page,
                    'uuid' => $this->uuid,
                    'result' => false,
                    'created_at' => time(),
                    'date' => date('Y-m-d')
                ]);
        }
        return $this;
    }
}
