<?php

namespace App\Jobs;

use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\PairModel;
use App\Models\User\AuthKey;
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\FormidModel;
use App\Models\Common\TokenModel;
use App\Models\User\UserModel;
use App\Services\Log\NoticeLogService;
use Ixudra\Curl\Facades\Curl;

/**
 * 新用户通知第2天
 * Class NewOpenidNotice2Job
 * @package App\Jobs
 */
class NewOpenidNotice2Job 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;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->sendWx($this->openid) || $this->sendQQ($this->openid)) {
            $this->dispatchNotice3Job($this->openid);
        } else {
            if ($this->execCnt < 3) {
                NewOpenidNotice2Job::dispatch($this->openid, $this->execCnt + 1)->delay(Carbon::now()->addDay(1));
            }
        }
    }

    /**
     * 分发通知到第3天
     * @param  string  $openid
     * @return bool
     */
    public function dispatchNotice3Job(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);
        }
        NewOpenidNotice3Job::dispatch($openid)->delay($now->addDay(1));
    }

    /**
     * 发送微信通知
     * @param  string  $openid
     * @return bool
     */
    public function sendWx(string $openid)
    {
        $noticeLog = new NoticeLogService();
        $title = '新用户引导隔1日通知';
        $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'];
            if ($form->uid > 0) {
                $user = UserModel::findOrFail($form->uid);
                if ($user->login_at > mktime(0, 0, 0)) {
                    return true;
                }
                if (PairModel::where('uid', $user->uid)->exists() || $user->partner_id > 0) {
                    return true;
                }
            }

            $cnt = PairModel::where('stage_id', $stage_id)->count();
            $templates = array(
                [
                    'template' => 'vdZmmmUmHMyFLjV3CTvRANavzruks5fm5ixYegRfZ1U',
                    'data' => [
                        'keyword1' => array(
                            'value' => "报名未生效通知"
                        ),
                        'keyword2' => array(
                            'value' => "当前报名人数已达{$cnt}，完善报名信息，生效后才可以参与匹配心动的人哦"
                        ),
                        'keyword3' => array(
                            'value' => date("Y-m-d")
                        )
                    ]
                ],
                [
                    'template' => 'hc6Av4hGLXLzcVgc4JkDNmrYJ18rztBPU_NCfYUNy7U',
                    'data' => [
                        'keyword1' => array(
                            'value' => "报名未生效通知"
                        ),
                        'keyword2' => array(
                            'value' => ""
                        ),
                        'keyword3' => array(
                            'value' => "当前报名人数已达{$cnt}，完善报名信息，生效后才可以参与匹配心动的人哦"
                        ),
                        'keyword4' => array(
                            'value' => date("Y-m-d")
                        )
                    ]
                ],
            );
            $template = $templates[rand(0, count($templates) - 1)];
            $page = "pages/starter/starter?launch_type=fpdx" . "&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;
        }
    }

    /**
     * 发送QQ通知
     * @param  string  $openid
     * @return bool
     */
    public function sendQQ(string $openid)
    {
        try {
            $stage_id = ActivityModel::getActivitys()['next'];
            $auth = AuthKey::where('auth_key', $openid)->first();
            if (collect($auth)->isEmpty()) {
            } else {
                try {
                    $user = UserModel::findOrFail($auth->uid);
                    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) {
                }
            }

            $cnt = PairModel::where('stage_id', $stage_id)->count();
            $templates = array(
                [
                    'template_id' => '3cbfba30266dc0722475249d37a5c884',
                    'data' => [
                        'keyword1' => array(
                            'value' => "报名未生效通知"
                        ),
                        'keyword2' => array(
                            'value' => "72小时恋爱体验"
                        ),
                        'keyword3' => array(
                            'value' => "当前报名人数已达{$cnt}，完善报名信息，生效后才可以参与匹配心动的人哦"
                        ),
                        'keyword4' => array(
                            'value' => date("Y-m-d")
                        )
                    ]
                ]
            );
            $template = $templates[rand(0, count($templates) - 1)];
            $title = '新用户引导隔1日通知';
            $page = "fpdx/pages/starter/starter";
            $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) {
            return false;
        }
    }
}
