<?php

namespace App\Services\WxMiniApp;

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

class Template extends Base
{


    /**
     * 微信接口地址
     * @var string
     */
    public const REQUEST_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send";


    protected $title;


    protected $uuid;


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

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

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

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

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

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


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

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


    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }


    public function setUuid($uuid)
    {
        $this->uuid = $uuid;

        return $this;
    }


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

        return $this;
    }

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

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

        return $this;
    }

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

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

        return $this;
    }

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

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

        return $this;
    }

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

        return $this;
    }


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


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


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

    /**
     * 发送通知
     * @return $this
     */
    public function send()
    {
        $form = $this->getFormId();
        if (!$form) {
            $this->err_code = 41027;
            $this->err_msg = 'form_id不存在';

            return $this;
        }

        // 发起微信请求
        $response = Curl::to($this->getRequestUrl())
            ->withData([
                'touser' => $this->openid,
                'template_id' => $this->template_id,
                'page' => $this->page,
                'form_id' => $form->form_id,
                'data' => $this->parameters,
                'emphasis_keyword' => $this->emphasis_keyword,
            ])
            ->asJsonRequest()
            ->asJsonResponse()
            ->post();

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


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

        dump($this->err_msg);
        dump($this->err_code);

        return $this;
    }

    /**
     * 获取form_id
     * @return mixed
     */
    protected function getFormId()
    {
        return FormIdModel::where('openid', $this->openid)
            ->where('public_id', $this->public_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;
    }
}
