<?php

declare(strict_types=1);

namespace app\common\model\core;

use Error;
use Exception;
use Generator;
use PHPExcel_Exception;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

/**
 * Class Excel
 * @package app\common\model\core
 */
class Excel
{


    /**
     * @param $filename
     * @param $columns
     * @return Error|Generator
     */
    public static function read($filename, $columns)
    {
        try {
        $excel = IOFactory::load($filename);
        if (is_error($excel)) {
            return error(-1, $excel->getMessage());
        }
        $sheet = $excel->getSheet(0);
            for ($i = 2; ; $i++) {
                $allEmpty = true;
                $row = [];
                $dataSet = [];
                foreach ($columns as $column) {
                    $row[$column['field']] = $sheet->getCell("{$column['column']}{$i}")->getValue();
                    if ($allEmpty && !empty($row[$column['field']])) {
                        $allEmpty = false;
                    }
                }
                if ($allEmpty) {
                    break;
                }
                $dataSet[] = $row;
                yield from $dataSet;
            }
        } catch (Exception $e) {
            return error(-1,$e->getMessage());
        }
    }

    /**
     * @param $title    string    文件名称
     * @param $headers   array   标题定义 ['列名称1', '列名称2']
     * @param $dataSet  array    导出的数据集, 和列名称对应
     */
    public static function write($title, $headers, $dataSet)
    {
        $o = new Spreadsheet();
        try {
            $sheet = $o->getSheet(0);
            $sheet->setTitle($title);
            $sheet->getColumnDimension('A')->setAutoSize(true);
            $sheet->getColumnDimension('B')->setAutoSize(true);
            $sheet->getColumnDimension('C')->setAutoSize(true);
            $sheet->getColumnDimension('D')->setAutoSize(true);
            $sheet->getColumnDimension('E')->setAutoSize(true);
            $sheet->getColumnDimension('F')->setAutoSize(true);
            $sheet->getColumnDimension('G')->setAutoSize(true);
            $sheet->getColumnDimension('H')->setAutoSize(true);
            $sheet->getColumnDimension('I')->setAutoSize(true);
            $i = 0;
            foreach ($headers as $header) {
                $sheet->setCellValueExplicitByColumnAndRow($i, 1, $header, DataType::TYPE_STRING);
                $i++;
            }
            $i = 2;
            foreach ($dataSet as $row) {
                $j = 0;
                foreach ($row as $cell) {
                    $sheet->setCellValueExplicitByColumnAndRow($j, $i, $cell, DataType::TYPE_STRING);
                    $j++;
                }
                $i++;
            }
            $filename = urlencode($title);
            header('content-type: application/xls');
            header('content-disposition: attachment; filename="' . $filename . '.xlsx"');
            $writer = new Xlsx($o);
            $writer->save('php://output');
            exit;
        } catch (Exception $e) {
            exit($e->getMessage());
        }
    }
}