<?php

namespace App\Jobs\Push;

use App\Modules\Push\Models\QappNewUserPushTask;
use App\Modules\Push\Models\QappNewUserPushTaskLog;
use App\Modules\Push\Models\QappPushUser;
use App\Modules\Push\Services\PushMessageService;
use App\Modules\Trade\Models\Order;
use App\Modules\User\Models\QappUserAddDestop;
use App\Modules\User\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class NewUserPushMsg implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    const condition = [
        'balance'     => [
            ['name' => '低于500', 'value' => 'a', 'condition' => [0, 500]],
            ['name' => '500-2000', 'value' => 'b', 'condition' => [500, 2000]],
            ['name' => '2000-5000', 'value' => 'c', 'condition' => [2000, 5000]],
            ['name' => '5000以上', 'value' => 'd', 'condition' => [5000, 0]],
            ['name' => '不限', 'value' => 'z', 'condition' => []]
        ],
        'paid'        => [
            ['name' => '不限', 'value' => 'z', 'condition' => []],
            ['name' => '未付费', 'value' => 'a', 'condition' => ['unpaid']],
            ['name' => '已付费', 'value' => 'b', 'condition' => ['paid']],
            ['name' => 'VIP用户', 'value' => 'c', 'condition' => ['vip']],
        ],
        'add_desktop' => [
            ['name' => '不限', 'value' => 'z', 'condition' => []],
            ['name' => '未加桌', 'value' => 'a', 'condition' => [0]],
            ['name' => '已加桌', 'value' => 'b', 'condition' => [1]],
        ]
    ];

    private $task;
    private $uid;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(int $uid, QappNewUserPushTask $task)
    {
        $this->uid = $uid;
        $this->task = $task;
    }

    private function createLog(): QappNewUserPushTaskLog
    {
        return QappNewUserPushTaskLog::create([
            'task_id' => $this->task->id,
            'app_id' => '',
            'uid' => $this->uid,
            'status' => 1,
        ]);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if (stripos($this->task->providers, $this->findUserProvider($this->uid)) >= 0) {
            $log = $this->createLog();
            $filter = $this->fliterUser($this->task->push_filter, $this->uid);
            if ($filter) {
                $result = null;
                try {
                    $result = PushMessageService::pushMessageToUser($this->uid, $this->task->title, $this->task->content, $this->task->url);
                }catch (\Exception $e){
                    myLog('NewUserPushMsg')->error($e);
                }
                $log->push_time = now();
                if ($result) {
                    $log->status = 3;
                    $log->push_result = json_encode($result);
                } else {
                    $log->status = 4;
                }
            } else {
                $log->status = 5;
            }
            $log->save();
        }
    }

    /**
     * 查找用户机型
     */
    private function findUserProvider(int $uid)
    {
        $push_user = QappPushUser::where('uid', $uid)->first();
        return $push_user ? $push_user->provider : '';
    }

    private function findUserBalance(int $uid): int
    {
        $user = User::find($uid);
        return $user ? $user->balance : 0;
    }

    private function fliterUser(string $filter, int $uid)
    {
        $result = true;
        $conditions = json_decode($filter, true);
        if ($conditions && is_array($conditions)) {
            foreach ($conditions as $key => $value) {
                $condition = $this->getCondition($key, $value);
                if ($result && $condition) {
                    switch ($key) {
                        case  'balance':
                            $balance = $this->findUserBalance($uid);
                            $result = $condition[0] ? $balance >= $condition[0] && ($condition[1] ? $balance <= $condition[1] : true) : true;
                            break;
                        case 'paid':
                            switch ($value) {
                                case 'unpaid':
                                    $result = !Order::where('uid', $uid)->where('status', 'PAID')->exists();
                                    break;
                                case 'paid':
                                    $result = Order::where('uid', $uid)->where('status', 'PAID')->exists();
                                    break;
                                case 'vip':
                                    $result = Order::where('uid', $uid)->where('status', 'PAID')->where('order_type', 'YEAR')->exists();
                                    break;
                            }
                            break;
                        case 'add_desktop':
                            $result = ($value == QappUserAddDestop::where('uid', $uid)->where('status', 1)->exists());
                            break;
                    }
                }
            }
        }
        return $result;
    }

    private function getCondition($key, $value)
    {
        if (array_key_exists($key, self::condition))
            foreach (self::condition[$key] as $item) {
                if ($item['value'] == $value) {
                    return $item['condition'];
                }
            }
        return '';
    }
}
