<?php

namespace Modules\User\Http\Controllers\Admin;

use App\Admin\Traits\WithUploads;
use EasyWeChat\Kernel\Http\StreamResponse;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Support\Facades\Storage;
use Modules\User\Models\UserChannel;

class ChannelController extends AdminController
{
    use WithUploads;

    protected $title = '渠道管理';

    public function grid(): Grid
    {
        $grid = new Grid(new UserChannel());

        $grid->disableFilter();

        $grid->column('name', '名称');
        $grid->column('code', '渠道码');
        $grid->column('mini_path', '小程序地址');
        $grid->column('mini_code', '小程序码')->display(function () {
            return Storage::url($this->mini_code);
        })->image();
        $grid->column('official_code', 'h5二维码')->display(function () {
            return Storage::url($this->official_code);
        })->image();

        $grid->column('status', '状态')->bool();

        return $grid;
    }

    protected function form(): Form
    {
        $form = new Form(new UserChannel());

        $form->text('name', '名称')->required();
        $this->cover($form);
        $form->text('code', '渠道码')->required();
        $form->text('mini_path', '小程序路径')->required();

        $form->switch('status', '显示')->default(1);

        $form->saved(function (Form $form) {
            $url  = 'channel/code';
            $info = $form->model();

            //h5
            $base64_img = $info->official_code_base64;
            preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $res);
            $base64_img = base64_decode(str_replace($res[1], '', $base64_img));
            $h5Name     = 'official_code_'.$info->id.'.png';
            $H5path     = $url.'/'.$h5Name;
            Storage::put($H5path, $base64_img);
            $data['official_code'] = $H5path;

            //小程序
            $app            = app('wechat.mini_program');
            $arr['channel'] = $info->code;
            $str            = $info->mini_path.'?'.http_build_query($arr);
            $response       = $app->app_code->getQrCode($str);

            if ($response instanceof StreamResponse) {
                $file              = $response->saveAs(storage_path('app/public/'.$url), 'mini_code_'.$info->id.'.png');
                $data['mini_code'] = $url.'/'.$file;
            }

            $form->model()->update($data);

        });
        return $form;
    }

}