<?php

namespace App\Admin\Actions;

use App\Models\User;
use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use PhpOffice\PhpWord\Exception\CopyFileException;
use PhpOffice\PhpWord\Exception\CreateTemporaryFileException;
use PhpOffice\PhpWord\TemplateProcessor;
use RuntimeException;

class DestroyData extends RowAction
{

    public $name = '数据导出';

    public function dialog()
    {
        $this->confirm('确定要销毁数据么，一旦操作不可恢复？');
    }

    public function handle(Model $model): Response
    {
        try {
            if ($model->archives) {
//                return $this->response()->error('数据销毁失败')->refresh();
            }
            // 先做存档
            $archives = [];

            foreach ($model->items as $key => $item) {
                $archives[$key] = [
                    'item_id'   => $item->id,
                    'item_name' => $item->name,
                    'total'     => User::where('type', 0)->count(),
                    'sign'      => User::where('type', 0)->where('sign', 1)->count(),
                    'tickets'   => $item->logs()->sum('result'),
                ];
            }
            $model->archives = $archives;
            $model->save();

            if ($model->type == 'diff') {
                $download = $this->exportDiff($model);
            } else {
                $download = $this->exportEqual($model);
            }

            $model->logs()->delete();

            return $this->response()->success('数据销毁完成')->refresh()->download($download);
        } catch (RuntimeException $exception) {
            return $this->response()->error('数据销毁失败'.$exception->getMessage())->refresh();
        }
    }

    /**
     * Notes   : 等额数据导出
     *
     * @Date   : 2022/5/4 15:39
     * @Author : <Jason.C>
     * @param $vote
     * @return string
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     */
    public function exportEqual($vote): string
    {
        $templateProcessor = new TemplateProcessor(storage_path('app/public/DENG_FEN.docx'));

        $templateProcessor->setValue('TOTAL', $vote->logs()->distinct('user_id')->count());
        $templateProcessor->setValue('TITLE', strip_tags($vote->title));

        $i   = 0;
        $tpl = '';
        foreach ($vote->items as $item) {
            $i++;
            $tpl .= $i.'. '.$item->name.'  '.$item->logs()->sum('result')." 票 <w:br />";
        }

        $templateProcessor->setValue('LOOPS', $tpl);
        $save = 'download_'.uniqid().'.docx';
        $templateProcessor->saveAs(storage_path('app/public/'.$save));

        return '/storage/'.$save;
    }

    /**
     * Notes: 差额数据倒出
     *
     * @Author: <C.Jason>
     * @Date  : 2020/5/7 4:34 下午
     * @param $vote
     * @return string
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     */
    protected function exportDiff($vote): string
    {
        $templateProcessor = new TemplateProcessor(storage_path('app/public/CHA_E.docx'));

        $templateProcessor->setValue('TOTAL', $vote->logs()->distinct('user_id')->count());
        $templateProcessor->setValue('TITLE', $vote->title);
        $templateProcessor->setValue('DATE', date('Y年m月d日', time()));

        $data = $vote->items;

        $data = $data->sortByDesc(function ($item) {
            return $item->logs()->sum('result');
        });

        $i   = 0;
        $tpl = '';
        foreach ($data as $item) {
            $i++;
            $tpl .= $i.'. '.$item->name.'  '.$item->logs()->sum('result')." 票<w:br />";
        }

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

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

        return '/storage/'.$save;
    }

}
