<?php

namespace App\Jobs;

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

class WelcomeJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * @var string 用户身份
     */
    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;
    }

    /**
     * Execute the job.
     *
     * @return \Illuminate\Foundation\Bus\PendingDispatch
     */
    public function handle()
    {
        $openid = $this->openid;
        if ($this->sendQQ($openid) || $this->sendWx($openid)) {
            return $this->dispatchNotice2Job($openid);
        } else {
            if ($this->execCnt < 3) {
                return WelcomeJob::dispatch($openid, $this->execCnt + 1)->delay(Carbon::now()->addDay(1));
            }
        }
    }

    public function dispatchNotice2Job(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();
        if (time() < mktime(9, 0, 0)) {
            $now->addHours(9);
        }
        if (time() > mktime(23, 0, 0)) {
            $now->addHours(-1);
        }
        NewOpenidNotice2Job::dispatch($openid)->delay($now->addDay(1));
    }

    public function sendWx($openid): bool
    {
        $noticeLog = new NoticeLogService();
        $title = '新用户引导相互心动通知';
        $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();
            $nickname = "萌萌哒小象";
            if ($form->uid > 0) {
                try {
                    $user = UserModel::findOrFail($form->uid);
                    if (2 == $user->sex) {
                        $nickname = "爱睡觉的小象";
                    }
                } catch (\Exception $exception) {
                    try {
                        $openuser = OpenidUserModel::where('openid', $openid)->firstOrFail();
                        if (2 == $openuser->sex) {
                            $nickname = "爱睡觉的小象";
                        }
                    } catch (\Exception $exception) {
                    }
                }
            } else {
                try {
                    $openuser = OpenidUserModel::where('openid', $openid)->firstOrFail();
                    if (2 == $openuser->sex) {
                        $nickname = "爱睡觉的小象";
                    }
                } catch (\Exception $exception) {
                }
            }

            $contents = [
                "💕真开心！你心动的对象「{$nickname}」也心动了你",
                "💕你和「{$nickname}」相互心动了呢！快去看看吧"
            ];
            $content = $contents[mt_rand(0, 1)];
            $templates = array(
                [
                    'template' => 'lNEemth7Kml5ZmOvBcbo842h3whkYMM2c8d2YJOQlEU',
                    'data' => [
                        'keyword1' => array(
                            'value' => "你的心动通知"
                        ),
                        'keyword2' => array(
                            'value' => "{$nickname}&你相互心动啦"
                        ),
                        'keyword3' => array(
                            'value' => $content
                        )
                    ]
                ],
                [
                    'template' => 'Xcp8AnnJr-cJmDMcr9WyIQmKgpN4qu6q6lStS0ZAiqs',
                    'data' => [
                        'keyword1' => array(
                            'value' => "你的心动通知"
                        ),
                        'keyword2' => array(
                            'value' => "{$nickname}&你相互心动啦"
                        ),
                        'keyword3' => array(
                            'value' => $content
                        )
                    ]
                ],
                [
                    'template' => 'fsptIIrBoCB6ftxT_6-ApQeqGoE_rJsC5VBDPUbdScg',
                    'data' => [
                        'keyword1' => array(
                            'value' => "你的心动通知"
                        ),
                        'keyword2' => array(
                            'value' => "{$nickname}&你相互心动啦"
                        ),
                        'keyword3' => array(
                            'value' => $content
                        )
                    ]
                ],
            );
            $template = $templates[rand(0, count($templates) - 1)];

            $page = "pages/starter/starter?launch_type=free&url=%2Fpages%2Ffriend%2Ffriend&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, $template['data']);
                return false;
            } else {
                $noticeLog->record($openid, $title, "小程序模板消息", $uuid, 1, $template['data']);
                return true;
            }
        } catch (\Exception $exception) {
            $noticeLog->record($openid, $title, "小程序模板消息", $uuid, 0);
        }
        return false;
    }

    public function sendQQ($openid): bool
    {
        try {
            $nickname = "萌萌哒小象";
            $auth = AuthKey::where('auth_key', $openid)->first();
            if (collect($auth)->isEmpty()) {
                try {
                    $openuser = OpenidUserModel::where('openid', $openid)->firstOrFail();
                    if (2 == $openuser->sex) {
                        $nickname = "爱睡觉的小象";
                    }
                } catch (\Exception $exception) {
                }
            } else {
                $user = UserModel::findOrFail($auth->uid);
                if (2 == $user->sex) {
                    $nickname = "爱睡觉的小象";
                }
            }

            $contents = [
                "💕真开心！你心动的对象「{$nickname}」也心动了你",
                "💕你和「{$nickname}」相互心动了呢！快去看看吧"
            ];
            $content = $contents[mt_rand(0, 1)];
            $templates = array(
                [
                    'template_id' => 'f8c20ac9f919e9c480e957f4576048c7',
                    'data' => [
                        'keyword1' => array(
                            'value' => "你的心动通知"
                        ),
                        'keyword2' => array(
                            'value' => "{$nickname}&你相互心动啦"
                        ),
                        'keyword3' => array(
                            'value' => $content
                        )
                    ]
                ]
            );
            $template = $templates[rand(0, count($templates) - 1)];
            $title = '新用户引导相互心动通知';
            $page = "pages/friend/friend";
            $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;
            } else {
                return false;
            }
        } catch (\Exception $exception) {
            return false;
        }
    }
}
