<?php

namespace App\Services\NoticeService;

use App\Services\NoticeService\Channels\Channel;
use Ramsey\Uuid\Uuid;

class Notification
{

    protected $title;


    protected $uuid;


    protected $to_uid;


    public function __construct($to_uid)
    {
        $this->to_uid = $to_uid;
        $this->uuid = Uuid::uuid4()->toString();
    }

    /**
     * 发送
     * @return bool
     */
    public function send()
    {
        if (!$this->subscribe()) {
            return false;
        }
        if (!$this->throttle()) {
            return false;
        }

        $channels = $this->via();
        foreach ($channels as $channel) {
            $channel->setUuid($this->uuid);
            $channel->setPath($this->getPagePath());
            if ($channel->send()) {
                $this->logger($channel);

                return true;
            }
        }

        return false;
    }

    /**
     * 订阅开关
     * @return bool
     */
    protected function subscribe()
    {
        return true;
    }

    /**
     * 节流阀
     * @return bool
     */
    protected function throttle()
    {
        return true;
    }

    /**
     * 通知渠道
     * @return array
     */
    public function via(): array
    {
        return [];
    }

    /**
     * 跳转地址
     * @return string
     */
    protected function getPagePath()
    {
        return 'pages/index/index';
    }

    /**
     * 成功通知日志
     * @param  Channel  $channel
     * @return array
     */
    public function logger(Channel $channel)
    {
        $log = [
            'uuid' => $this->uuid,
            'title' => $this->title,
            'uid' => $this->to_uid,
            'notice_type' => $channel->getNoticeType(),
            'template_id' => $channel->getTemplateId(),
            'content' => $channel->getContent(),
            'result' => true,
            'page' => $this->getPagePath(),
            'created_at' => time(),
            'date' => date('Y-m-d'),
        ];
        if (app()->environment() == 'production') {
            \DB::connection('mysql_datalog')->table("notice_logs")->insert($log);
        }

        return $log;
    }


    /**
     * 失败日志
     * @param string $account
     */
    public function failLogger($account)
    {
        if (app()->environment() == 'production') {
            \DB::connection('mysql_datalog')->table("notice_logs")->insert([
                'uuid' => $this->uuid,
                'title' => $this->title,
                'uid' => $this->to_uid,
                'notice_type' => $account,
                'content' => "",
                'result' => false,
                'created_at' => time(),
                'date' => date('Y-m-d'),
            ]);
        }
    }
}
