<?php

namespace App\Jobs;

use App\Models\Common\FormidModel;
use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\PairModel;
use App\Models\User\AuthKey;
use App\Models\User\OpenidUserModel;
use App\Models\User\UserModel;
use App\Services\QQMiniApp\Template;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\Common\TokenModel;
use App\Services\Log\NoticeLogService;
use Ixudra\Curl\Facades\Curl;

/**
 * 新用户通知第3天
 * Class NewOpenidNotice3Job
 * @package App\Jobs
 */
class NewOpenidNotice3Job implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    private $openid;

    /**
     * @var int 当前执行次数
     */
    private $execCnt;

    /**
     * Create a new job instance.
     *
     * @param  string  $openid
     * @param  int  $execCnt
     */
    public function __construct(string $openid, int $execCnt = 0)
    {
        $this->openid = $openid;
        $this->execCnt = $execCnt;
    }

    /**
     * @return bool
     */
    public function handle()
    {
        if ($this->sendWx($this->openid) || $this->sendQQ($this->openid)) {
            $this->dispatchNotice4Job($this->openid);
            return true;
        } else {
            if ($this->execCnt < 3) {
                NewOpenidNotice3Job::dispatch($this->openid, $this->execCnt + 1)->delay(Carbon::now()->addDay(1));
            }
            return false;
        }
    }

    /**
     * 分发通知到第4天
     * @param  string  $openid
     * @return bool
     */
    public function dispatchNotice4Job(string $openid)
    {
        try {
            $auth = AuthKey::where("auth_key", $openid)->firstOrFail();
            $user = UserModel::findOrFail($auth->uid);
            if (PairModel::where('uid', $user->uid)->exists() || $user->partner_id > 0) {
                return false;
            }
        } catch (\Exception $exception) {
        }
        $now = Carbon::now();
        time() < mktime(9, 0, 0) && $now->addHours(9);
        time() > mktime(23, 0, 0) && $now->addHours(-1);
        NewOpenidNotice4Job::dispatch($openid)->delay($now->addDay(1));
    }

    /**
     * 发送微信通知
     * @param  string  $openid
     * @return bool
     */
    public function sendWx(string $openid)
    {
        $noticeLog = new NoticeLogService();
        $title = '新用户引导隔2日通知';
        $uuid = uuid();

        try {
            $public_id = config('miniprogram.public_id');
            $tm = time() - 86400 * 6 + 43200;
            $form = FormidModel::where(array(
                ['openid', $openid],
                ['public_id', $public_id],
                ['state', 0],
                ['created_at', '>', $tm]
            ))->orderBy('id', 'asc')->firstOrFail();
            $stage_id = ActivityModel::getActivitys()['next'];
            $ta = "新朋友";
            $sex = 0;
            if ($form->uid > 0) {
                try {
                    $user = UserModel::findOrFail($form->uid);
                    $sex = $user->sex;

                    if ($user->login_at > mktime(0, 0, 0)) {
                        return true;
                    }
                    if (PairModel::where('uid', $user->uid)->exists() || $user->partner_id > 0) {
                        return true;
                    }
                } catch (\Exception $exception) {
                }
            } else {
                try {
                    $openuser = OpenidUserModel::where('openid', $openid)->firstOrFail();
                    $sex = $openuser->sex;
                } catch (\Exception $exception) {
                }
            }
            $sex == 1 && $ta = "小姐姐";
            $sex == 2 && $ta = "小哥哥";

            PairModel::where('stage_id', $stage_id)->count();
            $templates = array(
                [
                    'template' => 'vdZmmmUmHMyFLjV3CTvRANavzruks5fm5ixYegRfZ1U',
                    'data' => [
                        'keyword1' => array(
                            'value' => '今日推荐更新啦'
                        ),
                        'keyword2' => array(
                            'value' => "系统为你匹配了56个兴趣相投的{$ta}说不定其中就有你要找的人哦！"
                        ),
                        'keyword3' => array(
                            'value' => date("Y-m-d")
                        )
                    ]
                ],
                [
                    'template' => 'q5bSCp-hE2iotxBsEmEP4QS5113bsM06hpky-lJNI4Y',
                    'data' => [
                        'keyword1' => array(
                            'value' => '今日推荐更新啦'
                        ),
                        'keyword2' => array(
                            'value' => "系统为你匹配了56个兴趣相投的{$ta}说不定其中就有你要找的人哦！"
                        ),
                        'keyword3' => array(
                            'value' => '点此进入认识ta们~'
                        )
                    ]
                ]
            );

            $template = $templates[rand(0, count($templates) - 1)];
            $page = "pages/starter/starter?launch_type=free&url=%2Fpages%2Findex%2Findex" . "&log_type=notice&log_id={$uuid}";
            $access_token = TokenModel::getToken($public_id);
            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$access_token}";
            $data = [
                'touser' => $form->openid,
                'template_id' => $template['template'],
                'page' => $page,
                'form_id' => $form->form_id,
                'data' => $template['data']
            ];
            $result = Curl::to($url)->withData($data)->asJson()->post();
            $form->state = 1;
            $form->save();
            if (isset($result->errcode) && $result->errcode) {
                $noticeLog->record($openid, $title, "小程序模板消息", $uuid, 0);
                return false;
            } else {
                $noticeLog->record($openid, $title, "小程序模板消息", $uuid, 1, $template['data']);
                return true;
            }
        } catch (\Exception $exception) {
            $noticeLog->record($openid, $title, "小程序模板消息", $uuid, 0);
            return false;
        }
    }

    /**
     * 发送QQ通知
     * @param  string  $openid
     * @return bool
     */
    public function sendQQ(string $openid)
    {
        try {
            $ta = "新朋友";
            $sex = 0;
            $auth = AuthKey::where('auth_key', $openid)->first();
            if (collect($auth)->isEmpty()) {
                try {
                    $openuser = OpenidUserModel::where('openid', $openid)->firstOrFail();
                    $sex = $openuser->sex;
                } catch (\Exception $exception) {
                }
            } else {
                try {
                    $user = UserModel::findOrFail($auth->uid);
                    $sex = $user->sex;
                    if ($user->login_at > mktime(0, 0, 0)) {
                        return true;
                    }
                    if (PairModel::where('uid', $user->uid)->exists() || $user->partner_id > 0) {
                        return true;
                    }
                } catch (\Exception $exception) {
                }
            }
            $sex == 1 && $ta = "小姐姐";
            $sex == 2 && $ta = "小哥哥";
            $templates = array(
                [
                    'template_id' => '97888863d45a37a7ef08e5e1aedfbfe1',
                    'data' => [
                        'keyword1' => array(
                            'value' => '今日推荐更新啦'
                        ),
                        'keyword2' => array(
                            'value' => "系统为你匹配了56个兴趣相投的{$ta}说不定其中就有你要找的人哦！"
                        ),
                        'keyword3' => array(
                            'value' => "点此进入认识ta们~"
                        )
                    ]
                ]
            );

            $template = $templates[rand(0, count($templates) - 1)];
            $title = '新用户引导隔2日通知';
            $page = "pages/index/index";
            $app = new Template(config("qqprogram.app_id"));
            $app->setTitle($title)
                ->setUuid(uuid())
                ->setParameters($template['data'])
                ->setTemplateId($template['template_id'])
                ->toUser($openid)
                ->setPage($page)
                ->send();
            if (0 == $app->getCode()) {
                return true;
            }
            return false;
        } catch (\Exception $exception) {
            dump($exception);
            return false;
        }
    }
}
