<?php

namespace App\Services\Notice;

use App\Models\Deed\InvitationCardModel;
use App\Models\Log\FeedLogModel;
use App\Models\PraiseModel;
use App\Models\User\UserModel;
use App\Services\QQMiniApp\Template;
use App\Services\Service;

class OldUserRetainedService extends Service
{
    public function send()
    {
        $users = UserModel::whereBetween(
            'login_at',
            [mktime(0, 0, 0) - 3 * 86400, mktime(0, 0, 0)]
        )->where('partner_id', '>', 0)->get([
            'uid',
            'partner_id',
            'sex',
        ]);
        foreach ($users as $user) {
            $this->qqNotice($user);
        }
    }

    public function qqNotice($user)
    {
        $cnt = FeedLogModel::where('partner_id', $user->partner_id)->whereBetween(
            'created_at',
            [mktime(0, 0, 0) - 86400, mktime(0, 0, 0)]
        )->count();
        if ($cnt <= 0) {
            return;
        }

        $sex = "小哥哥";
        1 == $user->sex && $sex = "小姐姐";
        $content = "昨天共有{$cnt}个{$sex}访问了你的主页";
        $thumbs = PraiseModel::where(array(['partner_id', $user->partner_id], ['type', 1]))->whereBetween(
            'create_at',
            [mktime(0, 0, 0) - 86400, mktime(0, 0, 0)]
        )->count();
        $invites = InvitationCardModel::where("invite_uid", $user->uid)->whereBetween(
            'created_at',
            [mktime(0, 0, 0) - 86400, mktime(0, 0, 0)]
        )->count();
        if ($thumbs > 0 || $invites > 0) {
            if ($thumbs > 0) {
                $content = $content . ",共收到了{$thumbs}个「心动」";
            }
            if ($invites > 0) {
                $content = $content . ",{$invites}个「心动邀请」";
            }
        } else {
            $rands = array(
                ",其中有" . rand(1, $cnt / 2) . "个人为你停留了20秒以上",
                ",有" . rand(1, $cnt / 2) . "个人距离你不到1km哦~",
            );
            $content = $content . $rands[rand(0, 1)];
        }

        $title = "QQ小程序留存通知";
        $page = "popularity/pages/watched/watched";
        $app = new Template(config("qqprogram.app_id"));
        $app->setTitle($title)
            ->setUuid(uuid())
            ->toUser($user->uid)
            ->setPage($page)
            ->setParameters([
                'keyword1' => array(
                    'value' => "人气值日报",
                ),
                'keyword2' => array(
                    'value' => $content,
                ),
                'keyword3' => array(
                    'value' => "今日推荐已更新，小象为你匹配了56个兴趣相投又好看的{$sex}，说不定其中就有你心动的人哦！",
                ),
            ])
            ->setTemplateId("97888863d45a37a7ef08e5e1aedfbfe1")
            ->send();
    }
}
