<?php

namespace App\Notifications;

use App\Channels\WechatMiniChannel;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Channels\DatabaseChannel;
use Illuminate\Notifications\Notification;
use Modules\User\Models\Identity;
use Modules\User\Models\IdentityMiddle;
use Modules\User\Models\User;

class SystemOpenVip extends Notification
{

    use Queueable;

    protected $identityMiddle;
    protected $identity;
    protected $title;
    protected $remark;
    protected $url;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(IdentityMiddle $identityMiddle)
    {
        $identity = $identityMiddle->identity;
        $remark   = '赠送'.$identity->stock.'箱水';
//        if ($identity->job == Identity::JOB_HH) {
//            $remark = '开启奖金模式';
//        }

        $this->title          = "恭喜您！开通{$identityMiddle->identity->name}成功！";
        $this->identityMiddle = $identityMiddle;
        $this->identity       = $identity;
        $this->remark         = $remark;
        $this->url            = config('user.web.base');
    }

    public function via(): array
    {
        return [DatabaseChannel::class, WechatMiniChannel::class];
    }

    /**
     * Notes: 开通会员
     *
     * @Author: 玄尘
     * @Date: 2022/8/9 10:44
     * @param  User  $notifiable
     * @return bool
     */
    public function toWeChat(User $notifiable): bool
    {
        if ($notifiable->isOfficialSubscribe()) {
            $app = app('wechat.official_account');

            $start_at = $this->identityMiddle->started_at ?? '';
            $end_at   = $this->identityMiddle->ended_at ?? '';
            $time     = $start_at.' ~ '.$end_at;
            if (empty($start_at) || empty($end_at)) {
                $time = '永久';
            }

            $app->template_message->send([
                'touser'      => $notifiable->wechat->official_openid,
                'template_id' => 'gtS1LS9Irw7h2RtQLT5Cxx4p28-k8PrPyH53HBU2oWk',
                'url'         => $this->url,
                'data'        => [
                    'first'    => $this->title,
                    'keyword1' => $time,
                    'keyword2' => $this->remark,
                    'remark'   => '',
                ],
            ]);

        }

        return true;
    }

    /**
     * 发送到数据库
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase(User $notifiable): array
    {
        return [
            'title'   => $this->title,
            'content' => $this->remark,
            'url'     => $this->url,
        ];
    }
}
