<?php

/**
 * 好友列表未读消息通知
 * 「收到心动邀请未读 + 发出心动邀请被接受未读 + 相互心动未读」
 * User: easyboom
 * Date: 2019/5/22
 * Time: 上午10:04
 */

namespace App\Services\Notice;

use App\Http\Controllers\Miniprogram\Core;
use App\Http\Controllers\Wechat\Kfaccount;
use App\Models\Deed\EachLikeModel;
use App\Models\Deed\InvitationCardModel;
use App\Models\User\Openid;
use App\Models\User\UserModel;
use App\Services\Deed\FriendService;
use App\Services\Log\NoticeLogService;
use App\Services\Service;
use Illuminate\Support\Facades\Redis;

class FriendsListUnreadMsgService extends Service
{
    // 每天2点加载(如：5-5)
    public function loadSendQueue()
    {
        $arrays = array();
        // 获取三天前(5-1)未读的消息
        $day = mktime(0, 0, 0) - 86400 * 4;
        EachLikeModel::where([['state', 1], ['read_at', 0]])->whereBetween('updated_at', [$day, $day + 86400])
            ->get()->map(function ($eachlike) use (&$arrays) {
                $arrays[$eachlike->tuid]['uid'] = $eachlike->tuid;
                empty($arrays[$eachlike->tuid]['eachlike']) && $arrays[$eachlike->tuid]['eachlike'] = [];
                array_push($arrays[$eachlike->tuid]['eachlike'], $eachlike->id);
            });
        InvitationCardModel::where([['send_read', 0]])->whereBetween('created_at', [$day, $day + 86400])
            ->get()->map(function ($send_invite) use (&$arrays) {
                $arrays[$send_invite->uid]['uid'] = $send_invite->uid;
                empty($arrays[$send_invite->uid]['send_invite']) && $arrays[$send_invite->uid]['send_invite'] = [];
                array_push($arrays[$send_invite->uid]['send_invite'], $send_invite->id);
            });
        // 获取两天前(5-2)未读的消息
        $day = mktime(0, 0, 0) - 86400 * 3;
        EachLikeModel::where([['state', 1], ['read_at', 0]])->whereBetween('updated_at', [$day, $day + 86400])
            ->get()->map(function ($eachlike) use (&$arrays) {
                $arrays[$eachlike->tuid]['uid'] = $eachlike->tuid;
                empty($arrays[$eachlike->tuid]['eachlike']) && $arrays[$eachlike->tuid]['eachlike'] = [];
                array_push($arrays[$eachlike->tuid]['eachlike'], $eachlike->id);
            });
        InvitationCardModel::where([['send_read', 0]])->whereBetween('created_at', [$day, $day + 86400])
            ->get()->map(function ($send_invite) use (&$arrays) {
                $arrays[$send_invite->uid]['uid'] = $send_invite->uid;
                empty($arrays[$send_invite->uid]['send_invite']) && $arrays[$send_invite->uid]['send_invite'] = [];
                array_push($arrays[$send_invite->uid]['send_invite'], $send_invite->id);
            });
        // 获取一天前(5-3)未读的消息
        $day = mktime(0, 0, 0) - 86400 * 2;
        EachLikeModel::where([['state', 1], ['read_at', 0]])->whereBetween('updated_at', [$day, $day + 86400])
            ->get()->map(function ($eachlike) use (&$arrays) {
                $arrays[$eachlike->tuid]['uid'] = $eachlike->tuid;
                empty($arrays[$eachlike->tuid]['eachlike']) && $arrays[$eachlike->tuid]['eachlike'] = [];
                array_push($arrays[$eachlike->tuid]['eachlike'], $eachlike->id);
            });
        ;
        InvitationCardModel::where([['send_read', 0]])->whereBetween('created_at', [$day, $day + 86400])
            ->get()->map(function ($send_invite) use (&$arrays) {
                $arrays[$send_invite->uid]['uid'] = $send_invite->uid;
                empty($arrays[$send_invite->uid]['send_invite']) && $arrays[$send_invite->uid]['send_invite'] = [];
                array_push($arrays[$send_invite->uid]['send_invite'], $send_invite->id);
            });
        InvitationCardModel::where([['read', 0], ['state', 0], ['expired_at', '>', time()]])->whereBetween(
            'created_at',
            [$day, $day + 86400]
        )
            ->get()->map(function ($invite) use (&$arrays) {
                $arrays[$invite->invite_uid]['uid'] = $invite->invite_uid;
                empty($arrays[$invite->invite_uid]['invite_me']) && $arrays[$invite->invite_uid]['invite_me'] = [];
                array_push($arrays[$invite->invite_uid]['invite_me'], $invite->id);
            });
        foreach ($arrays as $array) {
            Redis::rpush("{friendslist:unreadnotice:load}", json_encode($array));
        }
        Redis::set("friendslist:unreadnotice:total", count($arrays));
        Redis::expire("{friendslist:unreadnotice:load}", mktime(23, 30, 0) - time());
        Redis::expire("friendslist:unreadnotice:total", mktime(23, 30, 0) - time());
    }

    public function push()
    {
        $total = Redis::get("friendslist:unreadnotice:total") ?? 0;
        $sendCnt = intval(ceil($total / (15 * 1 * 12)));
        dump($sendCnt);

        for (
            $i = 0; $i < $sendCnt; $i++
        ) {
            $toJson = Redis::lpop("{friendslist:unreadnotice:load}");
            if (is_null($toJson)) {
                return false;
            }
            try {
                $toData = json_decode($toJson, true);
                dump($toData);
                list($bool, $nickname) = $this->isCanPush($toData);
                if (!$bool) {
                    dump($bool);
                    continue;
                }
                $to_uid = $toData['uid'];
                $user = UserModel::findOrFail($to_uid);
                $sex = (1 == $user->sex) ? "铁汁" : "小姐姐";
                $title = "好友列表未读消息激活通知";
                $uuid = uuid();
                $noticeLog = new NoticeLogService();
                try {
                    $fs = new FriendService();
                    $cntData = $fs->getListCnt($to_uid);
                    $cnt = $cntData['all'];
                    $openid = Openid::ofPublic($to_uid)->value('openid');
                    $page = "pages/starter/starter?log_type=notice&log_id={$uuid}&launch_type=free&url=%2Fpages%2Ffriend%2Ffriend";
                    // 客服消息
                    $kfcontent = "有来自{$nickname}的{$cnt}条好友消息待查看\n厉害了{$sex}，又扩列啦！\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);
                        continue;
                    }

                    // 服务号模版消息
                    $public_id = config('wechat.fpdx.public_id');
                    $template_id = "vj03Lys62tcWH0BAx2bKdDbzxBnhwe4Fhs3GXqbxkTg";
                    $data = [
                        'first' => [
                            'value' => "{$user->nickname}的心动通知\n",
                        ],
                        'keyword1' => [
                            'value' => "有来自{$nickname}的{$cnt}条好友消息待查看",
                        ],
                        'keyword2' => [
                            'value' => "恭喜{$sex}，又扩列啦！	\n",
                        ],
                        'remark' => [
                            'value' => "点此查看",
                            "color" => "#FF7E98",
                        ],
                    ];
                    $core = new Core();
                    $result = $core->template($to_uid, $template_id, $public_id, $page, $data);
                    if ($result) {
                        $noticeLog->record($to_uid, $title, "公众号模板消息", $uuid, 1, $data);
                        continue;
                    }

                    // 小程序模板消息
                    $templates = array(
                        [
                            'template' => 'lNEemth7Kml5ZmOvBcbo842h3whkYMM2c8d2YJOQlEU',
                            'data' => [
                                'keyword1' => array(
                                    'value' => "{$user->nickname}的心动通知",
                                ),
                                'keyword2' => array(
                                    'value' => "有来自{$nickname}的{$cnt}条好友消息待查看",
                                ),
                                'keyword3' => array(
                                    'value' => "厉害了{$sex}，又扩列啦！快去查看吧~",
                                ),
                            ],
                        ],
                        [
                            'template' => 'Xcp8AnnJr-cJmDMcr9WyIQmKgpN4qu6q6lStS0ZAiqs',
                            'data' => [
                                'keyword1' => array(
                                    'value' => "{$user->nickname}的心动通知",
                                ),
                                'keyword2' => array(
                                    'value' => "有来自{$nickname}的{$cnt}条好友消息待查看",
                                ),
                                'keyword3' => array(
                                    'value' => "厉害了{$sex}，又扩列啦！快去查看吧~",
                                ),
                            ],
                        ],
                        [
                            'template' => 'fsptIIrBoCB6ftxT_6-ApQeqGoE_rJsC5VBDPUbdScg',
                            'data' => [
                                'keyword1' => array(
                                    'value' => "{$user->nickname}的心动通知",
                                ),
                                'keyword2' => array(
                                    'value' => "有来自{$nickname}的{$cnt}条好友消息待查看",
                                ),
                                'keyword3' => array(
                                    'value' => "厉害了{$sex}，又扩列啦！快去查看吧~",
                                ),
                            ],
                        ],
                    );
                    $template = $templates[rand(0, count($templates) - 1)];
                    $core = new Core();
                    $bool = $core->miniTemplate(
                        $to_uid,
                        $template['template'],
                        "gh_01c089b58dda",
                        $page,
                        $template['data']
                    );
                    if ($bool) {
                        $noticeLog->record($to_uid, $title, "小程序模板消息", $uuid, 1, $template['data']);
                        continue;
                    }
                } catch (\Exception $exception) {
                    dump($exception);
                }
                $noticeLog->record($to_uid, $title, "发送失败", $uuid);
            } catch (\Exception $exception) {
                dump($exception);
                continue;
            }
        }

        return true;
    }

    // 判断是否发送
    public function isCanPush(array $data): array
    {
        try {
            if (isset($data['eachlike'])) {
                foreach ($data['eachlike'] as $eachlike_id) {
                    $eachlike = EachLikeModel::findOrFail($eachlike_id);
                    if (0 == $eachlike->read_at && 1 == $eachlike->state) {
                        $user = UserModel::findOrFail($eachlike->uid);

                        return [true, $user->nickname];
                    }
                }
            }
            if (isset($data['send_invite'])) {
                foreach ($data['send_invite'] as $invite_id) {
                    $invite = InvitationCardModel::findOrFail($invite_id);
                    if (0 == $invite->send_read) {
                        $user = UserModel::findOrFail($invite->invite_uid);

                        return [true, $user->nickname];
                    }
                }
            }
            if (isset($data['invite_me'])) {
                foreach ($data['invite_me'] as $invite_id) {
                    $invite = InvitationCardModel::findOrFail($invite_id);
                    if (0 == $invite->read && time() < $invite->expired_at) {
                        $user = UserModel::findOrFail($invite->uid);

                        return [true, $user->nickname];
                    }
                }
            }
        } catch (\Exception $exception) {
        }

        return [false, null];
    }
}
