<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/10
 * Time: 16:01
 */
namespace Modules\Base\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\MessageBag;

class DownloadController
{
    public function download()
    {
        $data = $this->responseData();

        return view('base::download')->with($data);
    }

    public function upload()
    {
        $data = $this->responseData();
        return view('base::upload')->with($data);
    }


    public function responseData(): array
    {
        return db_setting('apk', [
            'update_msg' => '未更新过',
            'update_time' => '',
            'version' => '',
            'download_url' => '/uploads/apk/latest.apk',
        ]);
    }

    public function saveApk(Request $request)
    {
        //dd($request->file);
        $request->validate([
           'file' => ['bail', 'required', 'file', function ($attribute, $value, $fail) {
               if ($value->getClientOriginalExtension() != 'apk') {
                   $fail('不是一个有效的APK文件');
               }
           }],
            'version' => ['required'],
            'password' => ['required', 'in:123456'],
        ]);

        $version = $request->get('version', false);

        Storage::disk('admin')->putFileAs('apk', $request->file, 'latest_'.$version.'.apk');

        if ($version && $version !='0.0.0') {
            $setting = db_setting('apk', []);
            db_setting_set('apk', array_merge($setting,
                [
                    'version' => $version,
                    'update_msg' => $request->update_msg,
                    'update_time' => date("Y-m-d H:i:s"),
                    'download_url' => '/uploads/apk/latest_'.$version.'.apk',
                ]));

        }

        //abort_if(($request->file->getClientOriginalExtension() != $type), 500, '类型错误');
        $message = new MessageBag(['type' => 'success', 'title' => '提示', 'message' => '上传成功']);
        session()->flash('success', $message);

        return back();
    }
}
