<?php

namespace App\Services\NoticeService\Channels;

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

class WeChatKfAccountChannel extends Channel
{


    /**
     * 消息类型
     */
    public const NOTICE_TYPE = "微信公众号客服消息";


    /**
     * 请求地址
     */
    public const REQUEST_URL = "https://api.weixin.qq.com/cgi-bin/message/custom/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";


    protected $page_content;


    /**
     * h5跳转地址
     * @var string
     */
    protected $url;


    /**
     * 发送文字内容
     * @var
     */
    protected $content;


    /**
     * 错误码
     * @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;
    }

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

        return $this;
    }


    /**
     * 设置h5地址
     * @param $url
     * @return $this
     */
    public function setUrl($url)
    {
        $this->url = $url;

        return $this;
    }


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


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


    /**
     * 设置内容文字
     * @param $content
     * @return $this
     */
    public function setContentString($content)
    {
        $this->content = $content;

        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
     */
    public function request()
    {
        $data = [
            'touser' => $this->openId,
            'msgtype' => 'text',
            'text' => [
                'content' => $this->getContentString(),
            ],
        ];
        $response = Curl::to($this->getRequestUrl())
            ->withData($data)
            ->asJson()
            ->post();

        $this->errCode = $response->errcode;
        $this->errMsg = $response->errmsg;

        return $this;
    }

    /**
     * 发送内容
     * @return false|string
     */
    public function getContentString()
    {
        $content = $this->page_content;
        if ($this->page) {
            $page = $this->getPagePath();
            $content = "<a href='{$this->url}' data-miniprogram-appid='wx4c1722a4055bd229' data-miniprogram-path='{$page}'>{$this->page_content}</a>";
        } elseif ($this->url) {
            $content = "<a href='{$this->url}'>{$this->page_content}</a>";
        }

        return sprintf($this->content, $content);
    }

    /**
     * 获取完全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 string
     */
    private function getRequestUrl()
    {
        $token = TokenModel::where('user_name', $this->appId)->value('access_token');

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

    /**
     * 记录日志
     * @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 ?: $this->url,
                    '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 ?: $this->url,
                    'uuid' => $this->uuid,
                    'result' => false,
                    'created_at' => time(),
                    'date' => date('Y-m-d'),
                ]);
        }

        return $this;
    }
}
