<?php

namespace BYDAuto\Controllers;

use BYDAuto\Actions\TestdriveCreateAction;
use BYDAuto\Foundation\Encryption;
use BYDAuto\Models\Testdrive;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class BYDAutoController extends Controller
{
    use ValidatesRequests;

    public function testdrive(Request $request)
    {
        $rules['name'] = ['required'];
        $rules['mobile'] = ['required'];
        $this->validate($request, $rules);
        $requestId = Str::uuid();
        $request->merge(['request_id' => $requestId]);

        $model = (new TestdriveCreateAction())->execute($request);
        // TestdrivePushJob::dispatch($model);

        return response()->json(['code' => 0, 'message' => '提交成功', 'request_id' => $requestId]);
    }

    // https://vm1112app.arsk.net/pkg/bydauto/leads-data-send
    // 车主频道车主认证功能：线索数据发送
    // spi.alipay.eco.mycar.leads.data.send
    // https://opendocs.alipay.com/pre-open/86118bff_spi.alipay.eco.mycar.leads.data.send?pathHash=d19083e7
    public function leadsDataSend(Request $request)
    {
        $input = $request->all();
        info('===== leadsDataSend', $input);
        $biz_content = $input['biz_content'] ?? '';
        throw_if(empty($biz_content), ValidationException::withMessages(['biz_content' => 'missing biz_content']));

        $key = 'f4LNNKURSfT4/p5ne4xXdW45vcUahojQDEb+dejxUq8=';
        try {
            $iv = str_repeat("\0", 16);
            $data = openssl_decrypt(base64_decode($biz_content), 'AES-256-CBC', base64_decode($key), OPENSSL_RAW_DATA, $iv);
            $data = json_decode($data, true);
            info('===== [leadsDataSend]', $data);
            // Testdrive::leadsDataSend($data);
        } catch (\Throwable $th) {
            info('===== [biz_content decrypt fail]', [$th->getMessage()]);
        }
        // 留咨成功 success 留咨失败 failed 重复留咨 duplicate submit 系统异常 system error
        $response = ['msg' => 'success', 'code' => '10000'];
        $output['response'] = json_encode($response);
        $output['sign'] = $this->sign($response);
        return response()->json($output);
    }

    // 行业云留资SPI接口 实现
    // https://vm1112app.arsk.net/pkg/bydauto/isaas
    public function isaas(Request $request)
    {
        $input = $request->all();
        info('===== bydautoController::isaas', $input);

        $biz_content = $input['biz_content'] ?? '';
        throw_if(empty($biz_content), ValidationException::withMessages(['biz_content' => 'missing biz_content']));

        $key = 'f4LNNKURSfT4/p5ne4xXdW45vcUahojQDEb+dejxUq8=';
        try {
            $iv = str_repeat("\0", 16);
            $data = openssl_decrypt(base64_decode($biz_content), 'AES-256-CBC', base64_decode($key), OPENSSL_RAW_DATA, $iv);
            $data = json_decode($data, true);
            Testdrive::isaas($data);
        } catch (\Throwable $th) {
            info('===== [biz_content decrypt fail]', [$th->getMessage()]);
        }
        // 留咨成功 success 留咨失败 failed 重复留咨 duplicate submit 系统异常 system error
        $response = ['msg' => 'success', 'code' => '10000'];
        $output['response'] = json_encode($response);
        $output['sign'] = $this->sign($response);
        return response()->json($output);
    }

    // 实现官方标准API 专享产品-灯火平台广告投放
    // 提供给特定广告代理商（例如 天猫），为广告主提供广告投放服务
    // https://vm1112app.arsk.net/pkg/bydauto/cluepackage
    // 官方定义的标准API 行业线索数据推送
    public function cluepackage(Request $request)
    {
        Testdrive::cluepackage($request->all());
        return response()->json(['response' => ['code' => '10000', 'msg' => 'Success']]);
    }

    // 支付宝支付通知（应用网关）https://vm1112app.arsk.net/pkg/bydauto/notice
    // 用于接收支付宝异步通知消息（例如From平台消息等），需要传入http(s)公网可访问的网页地址。选填，若不设置，则无法接收相应的异步通知消息
    public function notice(Request $request)
    {
        $input = $request->all();
        info('===== notice', $input);
        return response('');
    }

    protected function sign($input)
    {
        $pubkey = file_get_contents(storage_path('app/pkg/chery-crm/isaas/app_pub_RSA2048.txt'));
        $pubkey = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($pubkey, 64, "\n", true) . "\n-----END PUBLIC KEY-----";

        $privkey = file_get_contents(storage_path('app/pkg/chery-crm/isaas/app_priv_RSA2048.txt'));
        $privkey = "-----BEGIN PRIVATE-----\n" . wordwrap($privkey, 64, "\n", true) . "\n-----END PRIVATE-----";

        $encryption = new Encryption($pubkey, $privkey);

        $key = 'f4LNNKURSfT4/p5ne4xXdW45vcUahojQDEb+dejxUq8=';
        ksort($input);
        $input = json_encode($input, JSON_UNESCAPED_UNICODE);
        $secretText = $this->encrypt($input, $key);
        return $encryption->encrypt($secretText);
    }

    protected function encrypt($input, $key)
    {
        $iv = str_repeat("\0", 16);
        return base64_encode(openssl_encrypt($input, 'AES-256-CBC', base64_decode($key), OPENSSL_RAW_DATA, $iv));
    }
}
