<?php

namespace App\Admin\Actions;

use App\Models\Vote;
use Encore\Admin\Actions\Action;
use Encore\Admin\Actions\Response;
use Illuminate\Http\Request;
use PhpOffice\PhpWord\TemplateProcessor;

class ExportCha extends Action
{

    public    $name     = '差额倒出';

    protected $vote;

    protected $selector = '.export-cha';

    public function handle(Request $request): Response
    {
        $templateProcessor = new TemplateProcessor(storage_path('app/public/CHA_E.docx'));

        $vote = Vote::find(2);
        $templateProcessor->setValue('TOTAL', $vote->logs()->distinct('user_id')->count());
        $templateProcessor->setValue('TITLE', $vote->title);

        $i = 0;
        $tpl = '';
        foreach ($vote->items as $item) {
            $i++;
            $tpl .= $i . '. ' . $item->name . '  ' . $item->logs()->sum('result') . " 票\r";
        }

        $templateProcessor->setValue('TPL', $tpl);

        $save = 'chae_1.docx';
        $templateProcessor->saveAs(storage_path('app/public/' . $save));

        return $this->response()->success('倒出成功')->download('/storage/' . $save);
    }

    public function html(): string
    {
        return <<<HTML
        <a class="btn btn-sm btn-warning export-cha"><i class="fa fa-upload"></i> 差额数据倒出</a>
HTML;
    }

}
