<?php


namespace App\ExcelData\Services;


use App\Exceptions\ApiException;
use App\Common\Facades\OssFacade;
use App\Form\Facades\FormRecordFacade;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class FormRecordSumService implements WithMultipleSheets
{
    use Exportable;
    protected $params = [];

    /**
     * 设置参数
     * @param $params 详见:\App\Forms\Services\FormInfoService::getList
     * @return $this
     */
    public function setParams($params)
    {
        $this->params = $params;
        return $this;
    }

    /**
     * 设置sheet
     * @return array
     */
    public function sheets(): array
    {
        $sheets = [];
        //通过查询条件获取sheets基本信息
        $params = $this->params;
        $params['format_list'] = false;
        $data = FormRecordFacade::getFormRecordList($params);
        empty($data) && $data = [];
        if(empty($data)){
            throw new ApiException(40013);
        }
        $forms = mapByKey($data, 'form_id');
        /*$formIds = array_column($data, 'form_id');
        !empty($formIds) && $formIds = array_unique($formIds);*/

        $params = $this->params;
        foreach ($forms as $id => $form) {
            $params['form_id'] = $id;
            $sheets[] = (new FormService())->setParams($params);
        }
        return $sheets;
    }

    public function toOss()
    {
        $filename = 'form'.date('ymdHis').rand(0,99).'.xlsx';
        $filePath = storage_path('app/').$filename;
        $this->store($filename);
        $etag = md5_file($filePath);
        $url = OssFacade::uploadToOss($filePath, $filename, $etag);
        return $url;
    }
}
