<?php

namespace App\Notifications;

use App\Channels\WechatMiniChannel;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Channels\DatabaseChannel;
use Illuminate\Notifications\Notification;
use Modules\Mall\Models\Order;
use Modules\Mall\Models\OrderExpress;
use Modules\User\Models\User;

class SystemOrderDelivered extends Notification
{

    use Queueable;

    protected $order;
    protected $title;
    protected $url;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($title, Order $order, $url = '')
    {
        $this->title = $title;
        $this->order = $order;
        $this->url   = $url;
    }

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

    /**
     * Notes: 订单发货
     *
     * @Author: 玄尘
     * @Date: 2022/8/4 16:22
     * @param  User  $notifiable
     * @return bool
     */
    public function toWeChat(User $notifiable): bool
    {
        if ($notifiable->isOfficialSubscribe()) {
            $app    = app('wechat.official_account');
            $remark = '您的宝贝已经发货，请耐心等待';
            if ($this->order->express->type == OrderExpress::TYPE_LOGISTICS) {
                $remark .= ',经办人：'.$this->order->express->person;
            }

            $res = $app->template_message->send([
                'touser'      => $notifiable->wechat->official_openid,
                'template_id' => 'UvUA6wvPSegvT7i8IVrLipktbtCmyjtdnuKD8EvyOO8',
                'url'         => $this->url,
                'data'        => [
                    'first'    => $this->title,
                    'keyword1' => $this->order->order_no,
                    'keyword2' => $this->order->express->deliver_at,
                    'keyword3' => $this->order->express->express_id > 0 ? $this->order->express->express->name : '',
                    'keyword4' => $this->order->express->express_no ?? '',
                    'keyword5' => $this->order->express->getFullAddress(),
                    'remark'   => $remark,
                ],
            ]);
        }
        return true;
    }

    /**
     * Notes: 数据库
     *
     * @Author: 玄尘
     * @Date: 2022/8/4 16:38
     * @param  User  $notifiable
     * @return array
     */
    public function toDatabase(User $notifiable): array
    {
        return [
            'title'   => $this->title,
            'content' => '订单编号：'.$this->order->order_no.' 已发货',
            'url'     => $this->url,
        ];
    }
}
