<?php

namespace App\Services\Share;

use App\Http\Controllers\Miniprogram\Core;
use App\Http\Controllers\Wechat\Kfaccount;
use App\Models\NoticeModel;
use App\Models\PartnerModel;
use App\Models\User\AuthKey;
use App\Models\User\Openid;
use App\Models\User\UserModel;
use App\Services\Log\NoticeLogService;
use App\Services\Notice\ManageService;
use App\Services\NoticeService\Channels\WeChatTemplateChannel;
use App\Services\QQMiniApp\Template;
use App\Services\Service;

class NoticeService extends Service
{
    /**
     * 解锁进度提升-喜欢我的解锁
     * @param $to_uid
     * @param $invite_uid
     * @param $invite_id
     * @return bool
     * @throws \Exception
     */
    public function inviteToLock($to_uid, $invite_uid, $invite_id)
    {
        $title = "交友卡片-喜欢我的解锁";
        $uuid = uuid();
        $noticeLog = new NoticeLogService();
        try {
            $nms = new ManageService();
            if (!$nms->getNoticeByKey($to_uid, "fpdx_help_notice")) {
                $noticeLog->record($to_uid, $title, "取消订阅", $uuid);

                return false;
            }
            $user = UserModel::find($to_uid);
            $invite_user = UserModel::find($invite_uid);
            $public_id = config('wechat.fpdx.public_id');
            $template_id = '06XYI6xZMauy5D3gP8R7g3J0J_Jq5y7N5ZpcwTvi6mI';
            $page = "pages/starter/starter?log_type=notice&log_id={$uuid}&launch_type=free&url=%2Fpages%2Finvite-likeme-unlock%2Finvite-likeme-unlock%3Fpraise_id%3D{$invite_id}";
            $data = [
                'first' => [
                    'value' => "卡片解锁进度增加啦！\n",
                ],
                'keyword1' => [
                    'value' => "你的好友{$invite_user->nickname}为你增加了卡片解锁进度",
                ],
                'keyword2' => [
                    'value' => "\"喜欢我的\"卡片解锁\n",
                ],
                'remark' => [
                    'value' => "点此查看助力结果-若不想接收此消息，可在“我-通知开关”中关闭",
                    "color" => "#ff7e98",
                ],
            ];
            $core = new Core();
            if ($core->template($user->uid, $template_id, $public_id, $page, $data)) {
                $noticeLog->record($to_uid, $title, "公众号模板消息", $uuid, 1, $data);

                return true;
            }
        } catch (\Exception $e) {
            app('sentry')->captureException($e);
        }
        $noticeLog->record($to_uid, $title, "发送失败", $uuid);

        return false;
    }

    /**
     * 人气值好友助力-分享者
     * @param  int  $to_uid
     * @param  array  $help
     * @return bool
     */
    public function popularitySharehelp2ShareUser(int $to_uid, array $help)
    {
        $title = '人气值好友助力通知分享者';
        $uuid = uuid();
        $noticeLog = new NoticeLogService();
        $timelong = 2 + 8 * $help['isnew'];
        $helpuser = UserModel::findOrFail($help['help_uid']);


        $content = "你的好友@{$helpuser->nickname} 成功为你增加人气值 {$timelong}小时";

        // QQ小程序模版消息
        $auth = AuthKey::where(array(['auth_type', config("qqprogram.app_id")], ['uid', $to_uid]))->first();
        if (!collect($auth)->isEmpty()) {
            $page = "popularity/pages/help/help";
            $app = new Template(config("qqprogram.app_id"));
            $app->setTitle($title)
                ->setUuid(uuid())
                ->setParameters([
                    'keyword1' => [
                        'value' => "人气值提升啦！",
                    ],
                    'keyword2' => [
                        'value' => $content,
                    ],
                    'keyword3' => [
                        'value' => "人气值-增加曝光",
                    ],
                    'keyword4' => [
                        'value' => "点此查看我的人气值",
                    ],
                ])
                ->setTemplateId("172b97e61188c41c15477a48181ef6c0")
                ->toUser($to_uid)
                ->setPage($page)
                ->send();
        }

        $page = "pages/starter/starter?log_type=notice&log_id={$uuid}&launch_type=free&url=%2Fpopularity%2Fpages%2Fhelp%2Fhelp";
        // 公众号客服消息
        $openid = Openid::ofPublic($to_uid)->value('openid');
        $kfcontent = "{$content}\n\n<a data-miniprogram-appid='wx4c1722a4055bd229' data-miniprogram-path='{$page}'>查看我的人气值</a>";
        $result = Kfaccount::text([
            'touser' => $openid,
            'content' => $kfcontent,
            'kf_account' => 'notice@admin',
        ]);
        if ($result['code'] == 0) {
            $noticeLog->record($to_uid, $title, "公众号客服消息", $uuid, 1, $kfcontent);

            return true;
        }

        // 公众号模板消息
        $public_id = config('wechat.fpdx.public_id');
        $template_id = "06XYI6xZMauy5D3gP8R7g3J0J_Jq5y7N5ZpcwTvi6mI";
        $page = "popularity/pages/help/help";
        $parameters = [
            'first' => [
                'value' => "人气值提升啦～\n",
            ],
            'keyword1' => [
                'value' => $content . "\n",
            ],
            'keyword2' => [
                'value' => "人气值-增加曝光\n",
            ],
            'remark' => [
                'value' => "查看我的人气值",
                "color" => "#FF7E98",
            ],
        ];
        $app = (new WeChatTemplateChannel())->setAppId($public_id)
            ->toUser($to_uid)->setTitle($title)->setPage($page)
            ->setParameters($parameters)->setTemplateId($template_id)
            ->send();
        if (0 == $app->getCode()) {
            return true;
        }

        $public_id = "gh_c94c95866ca5";
        $template_id = "V9qPmFurdkeTRqjOCdWLUj8LMsLndAR3UwnWazi6ZfY";
        $page = "popularity/pages/help/help";
        $parameters = [
            'first' => [
                'value' => "人气值提升啦～\n",
            ],
            'keyword1' => [
                'value' => $content . "\n",
            ],
            'keyword2' => [
                'value' => "人气值-增加曝光\n",
            ],
            'remark' => [
                'value' => "查看我的人气值",
                "color" => "#FF7E98",
            ],
        ];
        $app = (new WeChatTemplateChannel())->setAppId($public_id)
            ->toUser($to_uid)->setTitle($title)->setPage($page)
            ->setParameters($parameters)->setTemplateId($template_id)
            ->send();
        if (0 == $app->getCode()) {
            return true;
        }

        $noticeLog->record($to_uid, $title, "发送失败", $uuid);

        return false;
    }

    /**
     * 人气值好友助力-助力者
     * @param  int  $to_uid
     * @param  array  $help
     * @return bool
     */
    public function popularitySharehelp2HelpUser(int $to_uid, array $help)
    {
        // 未关注服务号 | 无可上架交友卡片 | 卡片隐身
        $partner = PartnerModel::where('uid', $to_uid)->firstOrFail();
        if (
            isset($partner->is_sell)
            && 1 == $partner->is_sell
            && Openid::where([['uid', $to_uid], ['subscribe', 1], ['public_id', 'gh_b598cb7474d8']])->exists()
        ) {
            return false;
        }
        $title = '人气值好友助力通知助力者';
        $uuid = uuid();
        $noticeLog = new NoticeLogService();
        $timelong = 2 + 8 * $help['isnew'];
        $shareuser = UserModel::findOrFail($help['share_uid']);

        // QQ小程序模版消息
        $auth = AuthKey::where(array(['auth_type', config("qqprogram.app_id")], ['uid', $to_uid]))->first();
        if (!collect($auth)->isEmpty()) {
            $page = "popularity/pages/score/score";
            $app = new Template(config("qqprogram.app_id"));
            $app->setTitle($title)
                ->setUuid(uuid())
                ->setParameters([
                    'keyword1' => array(
                        'value' => "助力成功",
                    ),
                    'keyword2' => array(
                        'value' => "你成功为你的好友@{$shareuser->nickname} 助力",
                    ),
                    'keyword3' => array(
                        'value' => "人气值-增加曝光",
                    ),
                    'keyword4' => array(
                        'value' => "点此查看我的人气值",
                    ),
                ])
                ->setTemplateId("172b97e61188c41c15477a48181ef6c0")
                ->toUser($auth->auth_key)
                ->setPage($page)
                ->send();
        }

        $public_id = config("wechat.fpdx.public_id");
        $template_id = "06XYI6xZMauy5D3gP8R7g3J0J_Jq5y7N5ZpcwTvi6mI";
        $page = "popularity/pages/score/score";
        $parameters = [
            'first' => [
                'value' => "你成功为你的好友@{$shareuser->nickname} 助力\n",
            ],
            'keyword1' => [
                'value' => "助力成功\n",
            ],
            'keyword2' => [
                'value' => "人气值-增加曝光\n",
            ],
            'remark' => [
                'value' => "点此查看你的人气值",
                "color" => "#FF7E98",
            ],
        ];
        $app = (new WeChatTemplateChannel())->setAppId($public_id)
            ->toUser($to_uid)->setTitle($title)->setPage($page)
            ->setParameters($parameters)->setTemplateId($template_id)
            ->send();
        if (0 == $app->getCode()) {
            // 发送系统消息
            NoticeModel::create([
                'type' => 5,
                'uid' => $to_uid,
                'create_at' => time(),
                'title' => "成功助力提醒",
                'content' => "你成功为你的好友@{$shareuser->nickname} 新增人气值{$timelong}小时",
                'tab_content' => '点此了解人气值',
                'tab_url' => '/popularity/pages/score/score',
            ]);

            return true;
        }

        $public_id = "gh_c94c95866ca5";
        $template_id = "V9qPmFurdkeTRqjOCdWLUj8LMsLndAR3UwnWazi6ZfY";
        $page = "popularity/pages/score/score";
        $parameters = [
            'first' => [
                'value' => "你成功为你的好友@{$shareuser->nickname} 助力\n",
            ],
            'keyword1' => [
                'value' => "助力成功\n",
            ],
            'keyword2' => [
                'value' => "人气值-增加曝光\n",
            ],
            'remark' => [
                'value' => "点此查看你的人气值",
                "color" => "#FF7E98",
            ],
        ];
        $app = (new WeChatTemplateChannel())->setAppId($public_id)
            ->toUser($to_uid)->setTitle($title)->setPage($page)
            ->setParameters($parameters)->setTemplateId($template_id)
            ->send();
        if (0 == $app->getCode()) {
            // 发送系统消息
            NoticeModel::create([
                'type' => 5,
                'uid' => $to_uid,
                'create_at' => time(),
                'title' => "成功助力提醒",
                'content' => "你成功为你的好友@{$shareuser->nickname} 新增人气值{$timelong}小时",
                'tab_content' => '点此了解人气值',
                'tab_url' => '/popularity/pages/score/score',
            ]);

            return true;
        }

        // 小程序模板消息
        $public_id = config('miniprogram.public_id');
        $template_id = "IFUqurIlP88yg1KJDSGI3zAA0oRSRLFaxgeZerTrbe4";
        $data = [
            'keyword1' => [
                'value' => "你成功为你的好友@{$shareuser->nickname} 助力\n",
            ],
            'keyword2' => [
                'value' => "助力成功\n",
            ],
            'keyword3' => [
                'value' => "人气值-增加曝光\n",
            ],
            'keyword4' => [
                'value' => "点此查看你的人气值",
            ],
        ];
        $core = new Core();
        $result = $core->miniTemplate($to_uid, $template_id, $public_id, $page, $data);
        if ($result) {
            $noticeLog->record($to_uid, $title, "小程序模板消息", $uuid, 1, $data);
            // 发送系统消息
            NoticeModel::create([
                'type' => 5,
                'uid' => $to_uid,
                'title' => "成功助力提醒",
                'content' => "你成功为你的好友@{$shareuser->nickname} 新增人气值{$timelong}小时",
                'tab_content' => '点此了解人气值',
                'tab_url' => '/popularity/pages/score/score',
            ]);

            return true;
        }
        $noticeLog->record($to_uid, $title, "发送失败", $uuid);

        return false;
    }

    /**
     * 人气值助力时间到期提醒
     * @param  int  $to_uid
     * @return bool
     */
    public function popularitySharehelpExpire(int $to_uid)
    {
        $title = '人气值好友助力时间到期通知';
        $uuid = uuid();
        $qquuid = uuid();
        $noticeLog = new NoticeLogService();

        try {
            $content = "你新增的人气值将于10分钟后停止加持，到期后将回归原有人气值。维持人气值将获得更多的曝光机会哦。";
            // QQ小程序模版消息
            $auth = AuthKey::where(array(['auth_type', config("qqprogram.app_id")], ['uid', $to_uid]))->first();
            if (!collect($auth)->isEmpty()) {
                $page = "popularity/pages/help/help";

                $app = new Template(config("qqprogram.app_id"));
                $app->setTitle($title)
                    ->setUuid(uuid())
                    ->setParameters([
                        'keyword1' => array(
                            'value' => "人气值变化提醒",
                        ),
                        'keyword2' => array(
                            'value' => "助力到期",
                        ),
                        'keyword3' => array(
                            'value' => $content,
                        ),
                    ])
                    ->setTemplateId("97888863d45a37a7ef08e5e1aedfbfe1")
                    ->toUser($auth->auth_key)
                    ->setPage($page)
                    ->send();
            }

            // 公众号客服消息
            $openid = Openid::ofPublic($to_uid)->value('openid');
            $page = "pages/starter/starter?log_type=notice&log_id={$uuid}&launch_type=free&url=%2Fpopularity%2Fpages%2Fhelp%2Fhelp";
            $kfcontent = "{$content}\n\n点击【<a data-miniprogram-appid='wx4c1722a4055bd229' data-miniprogram-path='{$page}'>这里</a>】查看详情";
            $result = Kfaccount::text([
                'touser' => $openid,
                'content' => $kfcontent,
                'kf_account' => 'notice@admin',
            ]);
            if ($result['code'] == 0) {
                $noticeLog->record($to_uid, $title, "公众号客服消息", $uuid, 1, $kfcontent);
                // 发送系统消息
                NoticeModel::create([
                    'type' => 5,
                    'uid' => $to_uid,
                    'title' => "助力新增人气值即将失效",
                    'content' => "你新增的人气值将于10分钟后停止加持，到期后将回归原有人气值。维持人气值将获得更多的曝光机会哦。",
                    'tab_content' => '查看详情',
                    'tab_url' => '/popularity/pages/help/help',
                ]);

                return true;
            }

            $public_id = "gh_c94c95866ca5";
            // 公众号模板消息
            $public_id = config('wechat.fpdx.public_id');
            $template_id = "ugxHaIxl5sFf2T00QZdCc0l4qELRUfEtw1HnCE7PDww";
            $page = "popularity/pages/help/help";
            $parameters = [
                'first' => [
                    'value' => $content . "\n",
                ],
                'keyword1' => [
                    'value' => "助力到期\n",
                ],
                'keyword2' => [
                    'value' => "增加人气值\n",
                ],
                'keyword3' => [
                    'value' => "人气值\n",
                ],
                'keyword4' => [
                    'value' => date('Y年m月d日') . "\n",
                ],
                'remark' => [
                    'value' => "点此查看详情",
                    "color" => "#FF7E98",
                ],
            ];
            $app = (new WeChatTemplateChannel())->setAppId($public_id)
                ->toUser($to_uid)->setTitle($title)->setPage($page)
                ->setParameters($parameters)->setTemplateId($template_id)
                ->send();
            if (0 == $app->getCode()) {
                // 发送系统消息
                NoticeModel::create([
                    'type' => 5,
                    'uid' => $to_uid,
                    'title' => "助力新增人气值即将失效",
                    'content' => "你新增的人气值将于10分钟后停止加持，到期后将回归原有人气值。维持人气值将获得更多的曝光机会哦。",
                    'tab_content' => '查看详情',
                    'tab_url' => '/popularity/pages/help/help',
                ]);

                return true;
            }

            $public_id = "gh_c94c95866ca5";
            $template_id = "HgmFhBPrOry3i647Zu9AF4Vcfs0MaIj8bE83-G5Kg6Q";
            $page = "popularity/pages/help/help";
            $parameters = [
                'first' => [
                    'value' => $content . "\n",
                ],
                'keyword1' => [
                    'value' => "助力到期\n",
                ],
                'keyword2' => [
                    'value' => "增加人气值\n",
                ],
                'keyword3' => [
                    'value' => "人气值\n",
                ],
                'keyword4' => [
                    'value' => date('Y年m月d日') . "\n",
                ],
                'remark' => [
                    'value' => "点此查看详情",
                    "color" => "#FF7E98",
                ],
            ];
            $app = (new WeChatTemplateChannel())->setAppId($public_id)
                ->toUser($to_uid)->setTitle($title)->setPage($page)
                ->setParameters($parameters)->setTemplateId($template_id)
                ->send();
            if (0 == $app->getCode()) {
                // 发送系统消息
                NoticeModel::create([
                    'type' => 5,
                    'uid' => $to_uid,
                    'title' => "助力新增人气值即将失效",
                    'content' => "你新增的人气值将于10分钟后停止加持，到期后将回归原有人气值。维持人气值将获得更多的曝光机会哦。",
                    'tab_content' => '查看详情',
                    'tab_url' => '/popularity/pages/help/help',
                ]);

                return true;
            }
        } catch (\Exception $e) {
        }
        $noticeLog->record($to_uid, $title, "发送失败", $uuid);

        return false;
    }

    /**
     * 人气值小花提升时间到期通知
     * @param  int  $to_uid
     * @return bool
     */
    public function popularityFlawerExpire(int $to_uid)
    {
        $title = '人气值小花提升时间到期通知';
        $noticeLog = new NoticeLogService();

        $content = "你新增的人气值将于10分钟后停止加持，到期后将回归原有人气值。维持人气值将获得更多的曝光机会哦。";

        // QQ小程序模版消息
        $auth = AuthKey::where(array(['auth_type', config("qqprogram.app_id")], ['uid', $to_uid]))->first();
        if (!collect($auth)->isEmpty()) {
            $page = "popularity/pages/score/score";
            $app = new Template(config("qqprogram.app_id"));
            $app->setTitle($title)
                ->setUuid(uuid())
                ->setParameters([
                    'keyword1' => array(
                        'value' => "人气值变化提醒",
                    ),
                    'keyword2' => array(
                        'value' => "助力到期",
                    ),
                    'keyword3' => array(
                        'value' => $content,
                    ),
                ])
                ->setTemplateId("97888863d45a37a7ef08e5e1aedfbfe1")
                ->toUser($to_uid)
                ->setPage($page)
                ->send();
        }

        $uuid = uuid();
        // 公众号客服消息
        $openid = Openid::ofPublic($to_uid)->value('openid');
        $page = "pages/starter/starter?log_type=notice&log_id={$uuid}&launch_type=free&url=%2Fpopularity%2Fpages%2Fscore%2Fscore";
        $kfcontent = "{$content}\n\n点击【<a data-miniprogram-appid='wx4c1722a4055bd229' data-miniprogram-path='{$page}'>这里</a>】查看详情";
        $result = Kfaccount::text([
            'touser' => $openid,
            'content' => $kfcontent,
            'kf_account' => 'notice@admin',
        ]);
        if ($result['code'] == 0) {
            $noticeLog->record($to_uid, $title, "公众号客服消息", $uuid, 1, $kfcontent);
            // 发送系统消息
            NoticeModel::create([
                'type' => 5,
                'uid' => $to_uid,
                'title' => "小fa新增人气值即将失效",
                'content' => "你新增的人气值将于10分钟后停止加持，到期后将回归原有人气值。维持人气值将获得更多的曝光机会哦。",
                'tab_content' => '查看详情',
                'tab_url' => '/popularity/pages/score/score',
            ]);

            return true;
        }

        // 公众号模板消息
        $public_id = config('wechat.fpdx.public_id');
        $template_id = "ugxHaIxl5sFf2T00QZdCc0l4qELRUfEtw1HnCE7PDww";
        $data = [
            'first' => [
                'value' => $content . "\n",
            ],
            'keyword1' => [
                'value' => "助力到期\n",
            ],
            'keyword2' => [
                'value' => "增加人气值\n",
            ],
            'keyword3' => [
                'value' => "人气值\n",
            ],
            'keyword4' => [
                'value' => date('Y年m月d日') . "\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);
            // 发送系统消息
            NoticeModel::create([
                'type' => 5,
                'uid' => $to_uid,
                'title' => "小fa新增人气值即将失效",
                'content' => "你新增的人气值将于10分钟后停止加持，到期后将回归原有人气值。维持人气值将获得更多的曝光机会哦。",
                'tab_content' => '查看详情',
                'tab_url' => '/popularity/pages/score/score',
            ]);

            return true;
        }
        $noticeLog->record($to_uid, $title, "发送失败", $uuid);

        return false;
    }
}
