<?php

/**
 * 人气值日报通知
 * User: easyboom
 * Date: 2019/4/26
 * Time: 下午3:08
 */

namespace App\Services\Notice;

use App\Http\Controllers\Miniprogram\Core;
use App\Http\Controllers\Wechat\Kfaccount;
use App\Models\Deed\InvitationCardModel;
use App\Models\Log\FeedLogModel;
use App\Models\PartnerModel;
use App\Models\PraiseModel;
use App\Models\User\Openid;
use App\Models\User\PopularityDayLogModel;
use App\Models\User\UserModel;
use App\Services\Log\NoticeLogService;
use App\Services\Service;
use App\Services\User\HomeService;
use Illuminate\Support\Facades\Redis;

class PopularityService extends Service
{

    // 加载人气值日报推送用户
    public function loadPushUsers()
    {
        $mktime = mktime(0, 0, 0);
        $partners = PartnerModel::where([['score', '>', 0], ['is_sell', 1]])->whereBetween(
            'login_at',
            [$mktime - 2 * 86400, $mktime - 86400]
        )->get(['uid']);
        foreach ($partners as $partner) {
            Redis::rpush("{popularity:daiy:push}", $partner->uid);
        }
        Redis::set("popularity:daiy:push:total", $partners->count());
        Redis::expire("popularity:daiy:push", mktime(23, 30, 0) - time());
        Redis::expire("popularity:daiy:push:total", mktime(23, 30, 0) - time());
    }

    // 发送日报
    public function daiyPush()
    {
        $total = Redis::get("popularity:daiy:push:total") ?? 0;
        $cnt = $total / (15 * 1 * 12) + 1;
        dump($cnt);
        $hs = new HomeService();
        for (
            $i = 0; $i < $cnt; $i++
        ) {
            $to_uid = Redis::lpop("{popularity:daiy:push}");
            dump("{$i}:{$to_uid}");
            try {
                $user = UserModel::find($to_uid);
                if (!$user) {
                    continue;
                }
                if ($user->login_at > mktime(0, 0, 0) - 86400) {
                    continue;
                }
                // 获取今日人气值
                $pdata = $hs->getPopularity($user->uid);
                $base = $pdata['base'];
                // 获取昨日人气值
                $yestoday = date('Y-m-d', strtotime("-1 day"));
                $yesPopularitylog = PopularityDayLogModel::where([
                    ['uid', $to_uid],
                    ['date', $yestoday],
                ])->firstOrFail();
                // 排名+百分比
                $ranktotal = PopularityDayLogModel::where([
                    ['location', $user->location],
                    ['date', $yestoday],
                    ['sex', $user->sex],
                ])->count();
                $lessrank_cnt = PopularityDayLogModel::where([
                    ['location', $user->location],
                    ['date', $yestoday],
                    ['sex', $user->sex],
                    ['popularity', '<', $yesPopularitylog->popularity],
                ])->count();
                $proportion = ceil($lessrank_cnt * 100 / $ranktotal);
                if ($yesPopularitylog->popularity > $base) {
                    $uporlow = "下降";
                } else {
                    $uporlow = "上升";
                }
                $disPopularity = abs($base - $yesPopularitylog->popularity);
                if (1 == $user->sex) {
                    $sex = "男生";
                } else {
                    $sex = "女生";
                }

                $title = "人气值日报通知";
                $uuid = uuid();
                $noticeLog = new NoticeLogService();
                try {
                    $inviteme = InvitationCardModel::where('invite_uid', $user->uid)->whereBetween(
                        'created_at',
                        [mktime(0, 0, 0) - 86400, mktime(0, 0, 0)]
                    )->count();
                    $thumbme = PraiseModel::where('partner_id', $user->partner_id)->whereBetween(
                        'created_at',
                        [mktime(0, 0, 0) - 86400, mktime(0, 0, 0)]
                    )->count();
                    $feedme = FeedLogModel::where('partner_id', $user->partner_id)->whereBetween(
                        'created_at',
                        [mktime(0, 0, 0) - 86400, mktime(0, 0, 0)]
                    )->count();
                    $remark = "";
                    $feedme > 0 && $remark .= "{$feedme}位访客, ";
                    $thumbme > 0 && $remark .= "{$thumbme}个心动, ";
                    $inviteme > 0 && $remark .= "{$inviteme}个心动邀请, ";
                    !empty($remark) && $remark = trim("昨日新增{$remark}", ", ") . "。";
                    $content = "{$user->nickname}的人气值日报 {$yestoday}\n\n你今日人气值为{$base}（不含附加分），较昨日对比{$uporlow}了{$disPopularity}，当前人气值打败了{$user->location}{$proportion}%的{$sex}。";
                    $openid = Openid::ofPublic($to_uid)->value('openid');
                    $page = "pages/starter/starter?launch_type=free&url=%2Fpopularity%2Fpages%2Fscore%2Fscore" . "&log_type=notice&log_id={$uuid}";
                    // 客服消息
                    $kfcontent = "{$content}{$remark}\n\n<a data-miniprogram-appid='wx4c1722a4055bd229' data-miniprogram-path='{$page}'>点此提升人气</a>";
                    $response = Kfaccount::text([
                        'touser' => $openid,
                        'content' => $kfcontent,
                        'kf_account' => 'notice@admin',
                    ]);
                    if ($response['code'] == 0) {
                        $noticeLog->record($to_uid, $title, "公众号客服消息", $uuid, 1, $kfcontent);
                        sleep(2);
                        continue;
                    }
                    // 模板消息
                    $public_id = config('wechat.fpdx.public_id');
                    $template_id = "kFkXgPPSqT_3GfLT_PFgCJYLMsqweWrU--GWt9zv-gE";
                    $data = [
                        'first' => [
                            'value' => "{$user->nickname}的人气值日报 {$yestoday}\n",
                        ],
                        'keyword1' => [
                            'value' => "{$user->nickname}",
                        ],
                        'keyword2' => [
                            'value' => date('Y-m-d H:i:m') . "\n",
                        ],
                        'remark' => [
                            'value' => "你今日人气值为{$base}（不含附加分），较昨日对比{$uporlow}了{$disPopularity}，当前人气值打败了{$user->location}{$proportion}%的{$sex}。{$remark}",
                            "color" => "#FF7E98",
                        ],
                    ];
                    $core = new Core();
                    $result = $core->template($to_uid, $template_id, $public_id, $page, $data, "miniprogram");
                    if ($result) {
                        $noticeLog->record($to_uid, $title, "公众号模板消息", $uuid, 1, $data);
                        sleep(1);
                        continue;
                    }
                } catch (\Exception $exception) {
                    app('sentry')->captureException($exception);
                }
                $noticeLog->record($to_uid, $title, "发送失败", $uuid);
            } catch (\Exception $exception) {
                continue;
            }
        }
    }
}
