<?php

namespace App\Jobs;

use App\Consts\SysConsts;
use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
use App\Modules\OfficialAccount\Models\OfficialAccount;
use App\Modules\Trade\Models\Order;
use App\Modules\User\Models\User;
use App\Modules\User\Models\UserEnv;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
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\Facades\Log;

/**
 * 抖音用户推送数据
 */
class TikTokUser implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    /**
     * 类型：充值
     */
    const charge = 'charge';
    /**
     * 类型：注册
     */
    const register = 'register';

    private $uid;
    private $type;

    /**
     * Create a new job instance.
     * @param int $uid
     * @param string $type 类型
     * @return void
     */
    public function __construct(int $uid, string $type)
    {
        $this->uid = $uid;
        $this->type = $type;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $user = User::find($this->uid);
        $user_env = UserEnv::where('uid', $this->uid)->first();
        if ($user && $user_env) {
            if ($this->type == self::charge) {
                $order = Order::where('uid', $this->uid)->where('status', 'PAID')->orderBy('id', 'desc')->first();
                $current_day_register = date('Y-m-d', strtotime($order->created_at)) ==  date('Y-m-d', strtotime($user->created_at));
                if ($order && $current_day_register && $order->price >= 30) {
                    $time = (string) $order->created_at;
                    $ip = $order->create_ip;
                    $count = Order::where('uid', $this->uid)->where('status', 'PAID')->where('price', '>=', '30')->count();
                    if ($count == 1) {
                        $amount = $order->price;
                    } else {
                        return;
                    }
                } else {
                    return;
                }
            } else {
                $time = (string) $user->created_at;
                $ip = $user->register_ip;
            }
            $wechat = OfficialAccount::where('distribution_channel_id', $user->distribution_channel_id)->orderBy('id', 'desc')->first();
            if ($wechat) {
                $params = [
                    'ip' => trim($ip),
                    'ua' => trim($user_env->ua),
                    'open_id' => trim($user->openid),
                    'account_id' => trim($wechat->alias),
                    'app_id' => trim($wechat->appid),
                    'source' => 'wdy',
                    'amount' =>  isset($amount) ? $amount : '',
                    'type' => $this->type,
                    'time' => $time,
                ];
                $params['sign'] = _sign($params, SysConsts::TIKTOK_KEY);
                $client = new Client(['timeout' => 4]);
                $url = 'https://newtrackapi.zhuishuyun.com/api/tiktokPushInfo';
                try {
                    $response = $client->post($url, ['form_params' => $params]);
                    $code = $response->getStatusCode();
                    $res = $code == 200 ? 'success' : 'fail';
                    Log::info('TikTokUser .' . $this->type . '. result : ' . $res . ' request params :' . json_encode($params) . ' http code: ' . $response->getStatusCode() . ' return content:' . $response->getBody()->getContents());
                } catch (ConnectException $e) {
                    Log::error($e->getMessage());
                }
            }
        }
    }
}
