<?php

namespace App\Jobs;

use App\Http\Controllers\Wechat\Kfaccount;
use App\Models\Common\FormidModel;
use App\Models\Common\TokenModel;
use App\Models\PraiseModel;
use App\Models\User\AuthKey;
use App\Models\User\MockThumbModel;
use App\Models\User\Openid;
use App\Models\User\OpenidUserModel;
use App\Models\User\UserModel;
use App\Services\Log\NoticeLogService;
use App\Services\NoticeService\Channels\WeChatTemplateChannel;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Ixudra\Curl\Facades\Curl;

/**
 * Class MockThumbJob
 * @package App\Jobs
 */
class MockThumbJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * @var mixed 用户id|openid
     */
    private $uidopenid;

    private $days = 1;

    private $isTiming = false;

    public const BOY = [1001, 1003, 1005, 1007, 1009, 1011];
    public const GIRL = [1002, 1004, 1006, 1008, 1010, 1012];

    /**
     * Create a new job instance.
     * 登录用户模拟点赞
     *
     * @param  mixed  $uidopenid
     * @param  int  $days
     * @param  int  $isTiming  mock途径 0:进入mock;1:定时mock(关注公众号);2:定时mock(未关注)
     */
    public function __construct($uidopenid, int $days = 1, int $isTiming = 0)
    {
        $this->uidopenid = $uidopenid;
        $this->days = $days;
        $this->isTiming = $isTiming;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            if (is_int($this->uidopenid)) {
                /** @var UserModel $user */
                $user = UserModel::findOrFail($this->uidopenid);
                if (0 == $user->partner_id) {
                    if (1 == $this->days && MockThumbModel::where('thumb_user', $user->uid)->exists()) {
                        return;
                    } else {
                        $whereuids = self::GIRL;
                        2 == $user->sex && $whereuids = self::BOY;

                        $mockedUids = MockThumbModel::where('thumb_user', $user->uid)->whereIn(
                            'uid',
                            $whereuids
                        )->get(['uid'])->pluck('uid')->toArray();
                        $uid = self::GIRL[rand(0, count(array_diff(self::GIRL, $mockedUids)) - 1)];
                        2 == $user->sex && $uid = self::BOY[rand(0, count(array_diff(self::BOY, $mockedUids)) - 1)];

                        MockThumbModel::create([
                            'uid' => $uid,
                            'thumb_user' => $user->uid,
                            'is_timing' => intval($this->isTiming)
                        ]);
                        $this->thumbMe($user->uid);
                    }
                } else {
                    if (
                        PraiseModel::where([['partner_id', $user->partner_id], ['type', 1]])->whereNotIn(
                            'uid',
                            [1, 2]
                        )->exists()
                    ) {
                        return;
                    } else {
                        $whereuids = self::GIRL;
                        2 == $user->sex && $whereuids = self::BOY;

                        $mockedUids = PraiseModel::where('partner_id', $user->partner_id)->whereIn(
                            'uid',
                            $whereuids
                        )->get(['uid'])->pluck('uid')->toArray();
                        $uid = self::GIRL[rand(0, count(array_diff(self::GIRL, $mockedUids)) - 1)];
                        2 == $user->sex && $uid = self::BOY[rand(0, count(array_diff(self::BOY, $mockedUids)) - 1)];

                        PraiseModel::updateOrCreate(['uid' => $uid, 'partner_id' => $user->partner_id], [
                            'uid' => $uid,
                            'partner_id' => $user->partner_id,
                            'create_at' => time(),
                            'created_at' => 1,
                            'updated_at' => time(),
                            'type' => 1,
                        ]);
                        $this->thumbMe($user->uid);
                    }
                }
            } else {
                if (1 == $this->days && MockThumbModel::where('thumb_user', $this->uidopenid)->exists()) {
                    return;
                } else {
                    $mockedUids = MockThumbModel::where(
                        'thumb_user',
                        $this->uidopenid
                    )->get(['uid'])->pluck('uid')->toArray();
                    $uid = self::GIRL[rand(0, count(array_diff(self::GIRL, $mockedUids)) - 1)];
                    try {
                        $user = OpenidUserModel::findOrFail($this->uidopenid);
                        2 == $user->sex && $uid = self::BOY[rand(0, count(array_diff(self::BOY, $mockedUids)) - 1)];
                    } catch (ModelNotFoundException $exception) {
                    }

                    MockThumbModel::create([
                        'uid' => $uid,
                        'thumb_user' => $this->uidopenid,
                        'is_timing' => intval($this->isTiming)
                    ]);
                    $this->thumbMe($this->uidopenid);
                }
            }
        } catch (\Exception $exception) {
        }
    }

    /**
     * @param int $to_user
     */
    private function thumbMe($to_user)
    {
        if (in_array($this->isTiming, [0, 1])) {
            $this->notice($to_user);
        } else {
            $this->noticeSms($to_user);
        }

        switch ($this->days) {
            case 1:
                $addDays = 2;
                break;
            case 3:
                $addDays = 1;
                break;
            default:
                return;
        }
        MockThumbJob::dispatch(
            $to_user,
            $this->days + $addDays,
            $this->isTiming
        )->delay(Carbon::now()->addDays($addDays));
    }

    /**
     * 发出通知
     * @param int|string $to_user
     * @return bool
     */
    public function notice($to_user)
    {
        if (is_int($to_user)) {
            $uid = $to_user;
            $openid = Openid::ofPublic($to_user, config("wechat.fpdx.public_id"))->value('openid');
            $miniopenid = AuthKey::where([
                ['auth_type', config("miniprogram.public_id")],
                ['uid', $uid]
            ])->value('auth_key');
        } else {
            $uid = 0;
            $openid = $to_user;
            $miniopenid = $openid;
        }

        $title = "模拟喜欢我的卡片通知";
        $uuid = uuid();
        $noticeLog = new NoticeLogService();

        $content = "❤️收到1个新的心动！";
        $remark = "";

        try {
            // 客服消息
            $page = "pages/starter/starter?log_type=notice&log_id={$uuid}&launch_type=free&url=%2Fpages%2Ffriend%2Ffriend";
            $kfcontent = "{$content}\n\n{$remark}\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($openid, $title, "公众号客服消息", $uuid, 1, $kfcontent);
                return true;
            }

            // fpdx模板消息
            $public_id = config('wechat.fpdx.public_id');
            $template_id = "ugxHaIxl5sFf2T00QZdCc0l4qELRUfEtw1HnCE7PDww";
            $page = "/pages/friend/friend";
            $parameters = [
                'first' => [
                    'value' => $content . "\n"
                ],
                'keyword1' => [
                    'value' => "收到一个新的心动"
                ],
                'keyword2' => [
                    'value' => "心动"
                ],
                'keyword3' => [
                    'value' => "心动通知"
                ],
                'keyword4' => [
                    'value' => date('Y-m-d')
                ],
                'remark' => [
                    'value' => $remark,
                    "color" => "#FF7E98"
                ],
            ];
            $app = (new WeChatTemplateChannel())->setAppId($public_id);
            $app->setTitle($title)->toUser($uid)->setPage($page)
                ->setTemplateId($template_id)->setParameters($parameters)
                ->send();
            if (0 == $app->getCode()) {
                return true;
            }

            // 小程序模板消息
            $templates = array(
                [
                    'template' => 'lNEemth7Kml5ZmOvBcbo842h3whkYMM2c8d2YJOQlEU',
                    'data' => [
                        'keyword1' => array(
                            'value' => "你的心动通知"
                        ),
                        'keyword2' => array(
                            'value' => "✉收到一个新的心动"
                        ),
                        'keyword3' => array(
                            'value' => $remark
                        )
                    ]
                ],
                [
                    'template' => 'Xcp8AnnJr-cJmDMcr9WyIQmKgpN4qu6q6lStS0ZAiqs',
                    'data' => [
                        'keyword1' => array(
                            'value' => "你的心动通知"
                        ),
                        'keyword2' => array(
                            'value' => "✉收到一个新的心动"
                        ),
                        'keyword3' => array(
                            'value' => $remark
                        )
                    ]
                ],
                [
                    'template' => 'fsptIIrBoCB6ftxT_6-ApQeqGoE_rJsC5VBDPUbdScg',
                    'data' => [
                        'keyword1' => array(
                            'value' => "你的心动通知"
                        ),
                        'keyword2' => array(
                            'value' => "✉收到一个新的心动"
                        ),
                        'keyword3' => array(
                            'value' => $remark
                        )
                    ]
                ],
            );
            $template = $templates[rand(0, count($templates) - 1)];
            $page = "pages/starter/starter?launch_type=free&url=%2Fpages%2Ffriend%2Ffriend&log_type=notice&log_id={$uuid}";
            $public_id = config("miniprogram.public_id");
            $form = FormidModel::where([
                ['openid', $miniopenid],
                ['public_id', $public_id],
                ['state', 0],
                ['created_at', '>', time() - 86400 * 6.5]
            ])->orderBy('created_at', 'asc')->first();
            if (collect($form)->isEmpty()) {
                return false;
            }
            $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) {
            } else {
                $noticeLog->record($openid, $title, "小程序模板消息", $uuid, 1, $template['data']);
                return true;
            }
        } catch (\Exception $exception) {
            dump($exception);
        }
        $noticeLog->record($openid, $title, "发送失败", $uuid);
        return false;
    }

    public function noticeSms($to_user)
    {
        $user = UserModel::find($to_user);
        if ($user->isEmpty() || empty($user->phone)) {
            return false;
        }

        // 发送短信
    }
}
