<?php

namespace App\Services\NoticeService\Channels;

use App\Models\Common\FormidModel;
use App\Models\Common\TokenModel;
use App\Models\User\AuthKey;
use Ixudra\Curl\Facades\Curl;

class WeChatMiniTemplateChannel extends Channel
{


    /**
     * 通知类型
     */
    public const NOTICE_TYPE = "微信小程序模板消息";


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


    /**
     * appId
     * @var
     */
    protected $appId;


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


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


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

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

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

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

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

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


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

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


    /**
     * 设置appId
     * @param $publicId
     * @return $this
     */
    public function setAppId($publicId)
    {
        $this->appId = $publicId;

        return $this;
    }

    /**
     * 获取通知的标题
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

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

        return $this;
    }

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

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

        return $this;
    }

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

        return $this;
    }

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

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

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

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

        return $this;
    }

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

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

        return $this;
    }

    /**
     * 发送者
     * @param $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->appId)->value('auth_key') ?: '';
        } else {
            $this->openId = $to_user;
        }

        return $this;
    }

    /**
     * 发送通知
     * @return $this
     */
    public function send()
    {
        $this->uuid = uuid();
        // 发起微信请求
        $this->request();


        $this->logger();

        return $this;
    }

    /**
     * 发送请求
     * @return $this
     */
    protected function request()
    {
        $form = FormidModel::where('openid', $this->openId)
            ->where('public_id', $this->appId)
            ->where('created_at', '>', time() - 6 * 86400)
            ->where('state', 0)
            ->orderBy('id', 'asc')
            ->first();
        if (collect($form)->isEmpty()) {
            // 成功或失败code/msg
            $this->errCode = 41027;
            $this->errMsg = "form_id为空";

            return $this;
        } else {
            $response = Curl::to($this->getRequestUrl())
                ->withData([
                    'touser' => $this->openId,
                    'template_id' => $this->templateId,
                    'page' => $this->getPagePath(),
                    'form_id' => $form->form_id,
                    'data' => $this->parameters,
                    'emphasis_keyword' => $this->emphasisKeyword,
                ])->asJson()
                ->post();
            // 核销表单
            $form->state = 1;
            $form->save();
            // 成功或失败code/msg
            $this->errCode = $response->errcode;
            $this->errMsg = $response->errmsg;
        }

        return $this;
    }

    /**
     * 获取通知的地址
     * @return string
     */
    protected function getRequestUrl()
    {
        $token = TokenModel::where('user_name', $this->appId)->value('access_token');

        return self::REQUEST_URL . "?access_token=" . $token;
    }

    /**
     * 获取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;
    }

    /**
     * 记录日志
     * @return $this
     */
    public function logger()
    {
        if ($this->errCode == 0) {
            \DB::connection('mysql_datalog')
                ->table("notice_logs")
                ->insert([
                    'uid' => $this->uid,
                    'openid' => $this->openId,
                    'title' => $this->title,
                    'notice_type' => self::NOTICE_TYPE,
                    'content' => $this->getContentString(),
                    'template_id' => $this->templateId,
                    '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->uid,
                    'openid' => $this->openId,
                    'title' => $this->title,
                    'notice_type' => self::NOTICE_TYPE,
                    'content' => $this->getContentString(),
                    'template_id' => $this->templateId,
                    'page' => $this->page,
                    'uuid' => $this->uuid,
                    'result' => false,
                    'created_at' => time(),
                    'date' => date('Y-m-d'),
                ]);
        }

        return $this;
    }

    /**
     * 发送内容
     * @return false|string
     */
    public function getContentString()
    {
        return $this->parameters
            ? json_encode($this->parameters, JSON_UNESCAPED_UNICODE)
            : '';
    }
}
