<?php

namespace App\Admin\Actions\Device;

use App\Model\DeviceInfo;
use App\Model\SystemConfig;
use App\Server\DeviceServer;
use EasyWeChat\Factory;
use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;

class downloadZip extends Action
{
    protected $selector = '.downloadZip';

    public function handle(Request $request)
    {
        // $request ...

       $devices = DeviceInfo::all(['device_name','id']);
       $result = [];
       $zip_file = public_path('qrcode.zip');
       $zip = new \ZipArchive();
       $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
       foreach ($devices as $device){
           $r = $this->generateImg($device->id,$device->device_city);
           if ($r)
           {
               $str = str_replace(['/','\\',':','*','"','<','>','|','?'],'_',$device->device_name);
               $zip->addFile($r, $str.".png");
           }
       }

       $zip->close();

       return $this->response()->download('/qrcode.zip');


    }


    public function generateImg($device_id,$device_city)
    {
        $wechat_app = SystemConfig::get('wechat_config');
        if (!$wechat_app || !isset($wechat_app['appId']) || !isset($wechat_app['appSecret'])) {
            return false;
        }
        $config = [
            'app_id' => $wechat_app['appId'],
            'secret' => $wechat_app['appSecret'],
            'response_type' => 'array'
        ];

        $app = Factory::miniProgram($config);


        try{
            $response = $app->app_code->getQrCode('pages/qrcode/qrcode?id='.$device_id.'&community='.$device_city,300);
        }catch (\Exception $exception){
            return false;
        }

        $filename = "error";
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs(public_path('upload/DeviceQRCODE'), request('id').'.jpg');
        }
        if ($filename == "error")
            return false;

        return public_path("upload/DeviceQRCODE/{$filename}");

    }

    public function html()
    {
        return <<<HTML
        <a href="javascript:$.admin.toastr.info('已经提交请求，处理完成会自动下载，请稍等！');" class="btn btn-sm btn-success downloadZip" style="margin-right: 10px;"><i class="fa fa-download"></i>&nbsp;下载设备图片</a>
HTML;
    }
}
