<?php

namespace App\Console\Commands\Notices;

use App\Managers\CouponManager;
use App\Models\Log\FeedLogModel;
use App\Models\NoticeModel;
use App\Models\PartnerModel;
use App\Models\User\AuthKey;
use App\Services\NoticeService\Channels\QQMiniTemplateChannel;
use App\Services\Pay\CouponService;
use App\Services\QQMiniApp\Template;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class QQCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'notice:qq {notice}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '通知-QQ小程序营销通知';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $notice = $this->argument('notice');

        switch ($notice) {
            case "first":
                dump($this->first());
                break;
            case "second":
                dump($this->second());
                break;
            case "third":
                dump($this->third());
                break;
        }
    }

    // 通知-QQ小程序老用户召回：第1条
    public function first()
    {
        $title = 'QQ小程序老用户召回-第1条';
        $filter_users = DB::connection('mysql_datalog')
            ->table("notice_logs")
            ->where([
                ['title', $title]
            ])
            ->pluck('uid')->toArray();
        $redis = Redis::Smembers("qq:olduser:callback:1");
        array_walk($redis, function (&$value) use ($filter_users) {
            $value = intval($value);
            array_push($filter_users, $value);
        });
        $sat = mktime(0, 0, 0) - 5 * 86400;
        $users = PartnerModel::whereBetween("login_at", [$sat, $sat + 86400])
            ->where('is_sell', 1)->whereNotIn('uid', $filter_users)->take(600)->get(['id', 'uid', 'sex', 'login_at']);

        foreach ($users as $user) {
            try {
                $sex = "小姐姐";
                $ta = "她";
                2 == $user->sex && $sex = "小哥哥";
                2 == $user->sex && $ta = "他";
                $cnt = FeedLogModel::where([
                        ['partner_id', $user->id],
                        ['created_at', '>', $user->login_at]
                    ])->count() + 1;
                $templates = array(
                    [
                        'template_id' => '8a4e8c0f73be381f49935dd20d79b6b9',
                        'data' => [
                            'keyword1' => array(
                                'value' => "刚才有一位{$sex}反复查看了你的个人主页。{$ta}离你只有0." . rand(1, 9) . "km哦！"
                            ),
                            'keyword2' => array(
                                'value' => "快来划卡片找到{$ta}~"
                            ),
                            'keyword3' => array(
                                'value' => "{$cnt}"
                            )
                        ]
                    ]
                );
                $template = $templates[rand(0, count($templates) - 1)];
                $page = "/pages/starter/starter";
                $app = new Template(config("qqprogram.app_id"));
                $app->setTitle($title)
                    ->setUuid(uuid())
                    ->setParameters($template['data'])
                    ->setTemplateId($template['template_id'])
                    ->toUser($user->uid)
                    ->setPage($page)
                    ->send();
                Redis::sadd("qq:olduser:callback:1", $user->uid);
            } catch (\Exception $exception) {
            }
        }
        Redis::expire("qq:olduser:callback:1", 86400);
        return true;
    }

    // 通知-QQ小程序老用户召回：第2条
    public function second()
    {
        $title = 'QQ小程序老用户召回-第2条';
        $filter_users = DB::connection('mysql_datalog')
            ->table("notice_logs")
            ->where([
                ['title', $title]
            ])
            ->pluck('uid')->toArray();
        $redis = Redis::Smembers("qq:olduser:callback:2");
        array_walk($redis, function (&$value) use ($filter_users) {
            $value = intval($value);
            array_push($filter_users, $value);
        });
        $sat = mktime(0, 0, 0) - 6 * 86400;
        $users = PartnerModel::whereBetween("login_at", [$sat, $sat + 86400])
            ->where('is_sell', 1)->whereNotIn('uid', $filter_users)->take(600)->get(['id', 'uid', 'sex', 'login_at']);

        foreach ($users as $user) {
            try {
                $sex = "小姐姐";
                $ta = "她";
                2 == $user->sex && $sex = "小哥哥";
                2 == $user->sex && $ta = "他";

                $templates = array(
                    [
                        'template_id' => '8a4e8c0f73be381f49935dd20d79b6b9',
                        'data' => [
                            'keyword1' => array(
                                'value' => "有一个距你0." . rand(1, 9) . "km的{$sex}喜欢了你，一直等不到你的回应…"
                            ),
                            'keyword2' => array(
                                'value' => "{$ta}曾收到过" . rand(101, 626) . "个喜欢"
                            ),
                            'keyword3' => array(
                                'value' => "快来划卡片找到{$ta}~"
                            )
                        ]
                    ]
                );
                $template = $templates[rand(0, count($templates) - 1)];
                $page = "/pages/starter/starter";
                $app = new Template(config("qqprogram.app_id"));
                $app->setTitle($title)
                    ->setUuid(uuid())
                    ->setParameters($template['data'])
                    ->setTemplateId($template['template_id'])
                    ->toUser($user->uid)
                    ->setPage($page)
                    ->send();
                Redis::sadd("qq:olduser:callback:2", $user->uid);
            } catch (\Exception $exception) {
            }
        }
        Redis::expire("qq:olduser:callback:2", 86400);
        return $users;
    }

    // 通知-QQ小程序老用户召回：第3条
    public function third()
    {
        $title = 'QQ小程序老用户召回-第3条';
        $filter_users = DB::connection('mysql_datalog')
            ->table("notice_logs")
            ->where([['title', $title], ['result', 1]])
            ->pluck('uid')->toArray();
        $redis = Redis::Smembers("qq:olduser:callback:3");
        array_walk($redis, function (&$value) use ($filter_users) {
            $value = intval($value);
            array_push($filter_users, $value);
        });
        $sat = mktime(0, 0, 0) - 7 * 86400;
        $users = PartnerModel::whereBetween("login_at", [$sat, $sat + 86400])
            ->where('is_sell', 1)->whereNotIn('uid', $filter_users)->take(600)->get(['uid']);
        foreach ($users as $user) {
            try {
                $sex = "小姐姐";
                2 == $user->sex && $sex = "小哥哥";
                $templates = array(
                    [
                        'template_id' => '8a4e8c0f73be381f49935dd20d79b6b9',
                        'data' => [
                            'keyword1' => array(
                                'value' => "有一个{$sex}想邀请你参加72小时恋爱体验活动~"
                            ),
                            'keyword2' => array(
                                'value' => "你们将组成CP，一起度过奇妙的72小时"
                            ),
                            'keyword3' => array(
                                'value' => "小象送你一张免费报名券，祝你顺利~"
                            )
                        ]
                    ]
                );
                $template = $templates[rand(0, count($templates) - 1)];

                $page = "/pages/starter/starter";
                $app = new Template(config("qqprogram.app_id"));
                $app->setTitle($title)
                    ->setUuid(uuid())
                    ->setParameters($template['data'])
                    ->setTemplateId($template['template_id'])
                    ->toUser($user->uid)
                    ->setPage($page)
                    ->send();
                if (0 == $app->getCode()) {
                    $couponManager = new CouponManager();
                    $couponManager->generateSuperVip72FreeCoupons($user->uid);
                    NoticeModel::create([
                        'uid' => $user->uid,
                        'title' => '如何使用“72小时恋爱体验”券报名',
                        'content' => "恭喜你中奖获得“72小时恋爱体验”券1张！点此教你如何使用体验券免费报名活动，直升最高匹配成功率！助力脱单~",
                        'type' => 5,
                        'type_id' => 0,
                        'create_at' => time(),
                        'update_at' => time(),
                        'tab_content' => '查看详情',
                        'tab_url' => 'https://mp.weixin.qq.com/s/mba8TwZP9dNYY0E2XF24wg',
                    ]);
                }
                Redis::sadd("qq:olduser:callback:3", $user->uid);
            } catch (\Exception $exception) {
            }
        }
        Redis::expire("qq:olduser:callback:3", 86400);
        return $users;
    }

    public function tmp()
    {
        $auths = AuthKey::where('auth_type', '1109365561')->get();
        foreach ($auths as $auth) {
            $app = new QQMiniTemplateChannel();
            $app->setAppId("1109365561")->toUser($auth->auth_key)
                ->setTitle("QQ小程序用户72h运营通知")
                ->setTemplateId("d149209e80157fd6e340a8049f7c02b7")
                ->setParameters([
                    'keyword1' => array(
                        'value' => "你有一条「约会」邀请信息~"
                    ),
                    'keyword2' => array(
                        'value' => "本周四12:00前"
                    ),
                    'keyword3' => array(
                        'value' => "假期太无聊，不想再打发时间？那...要不要和我恋爱约会呢，一起度过愉快的三天？点此报名72小时恋爱体验活动，接受「约会」邀请"
                    )
                ])->setPage("pages/starter/starter?launch_type=fpdx")
                ->send();
        }
    }
}
