<?php
/**
 * Created by PhpStorm
 * DateTime: 2022/11/5 0:31.
 *
 * @description
 */

namespace App\Http\Controllers\V1\Share;

use App\Http\Controllers\V1\Controller;
use App\Models\ShareConfig;
use App\Models\UserWithdraw;
use App\Services\Api\ErrorMsgServive;
use Illuminate\Http\JsonResponse;

class ShareController extends Controller
{
    public function income(): JsonResponse
    {
        // 已提现
        $been = UserWithdraw::where('user_id', \user()->id)
            ->where('status', 2)
            ->sum('price');
        // 待打款
        $wait = UserWithdraw::where('user_id', \user()->id)
            ->where('status', 1)
            ->sum('price');

        return $this->success([
            'been' => $been,
            'wait' => $wait,
        ]);
    }

    public function tips(): JsonResponse
    {
        $config = ShareConfig::first();

        return $this->success($config->withdraw_desc);
    }

    public function setting(): JsonResponse
    {
        $config = ShareConfig::first();

        return $this->success($config);
    }

    public function generateQrcode(): JsonResponse
    {
        $user = \user();
        if (!$user->scene_code || !$user->share_qrcode) {
            try {
                $app              = $this->getUniFactory($user->info->platform);
                $user->scene_code = md5(uniqid() . $user->id);
                if (1 == $user->info->platform) { // 抖音
                    $response = $app->generateQrcode();
                    $filename = public_path('static/qrcode_') . "{$user->scene_code}.png";
                    file_put_contents($filename, $response[0]);
                    $user->share_qrcode = save2Oss($filename);
                } elseif (2 == $user->info->platform) { // 快手
                    return $this->error('当前平台不支持');
                } elseif (3 == $user->info->platform) { // 微信
                    $response = $app->mini()->app_code->getUnlimit($user->scene_code, [
                        'page'  => 'pages/index/index',
                        'width' => 600,
                    ]);
                    if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                        $filename           = $response->saveAs(public_path('static'), "{$user->scene_code}.png");
                        $filename           = public_path('static/' . $filename);
                        $user->share_qrcode = save2Oss($filename);
                    }
                }
                $user->save();
            } catch (\Exception $ex) {
                ErrorMsgServive::write($ex, \request()->url());

                return $this->error('生成二维码失败');
            }
        }

        return $this->success(['url' => $user->share_qrcode]);
    }
}
