<?php

namespace Modules\Base\Http\Controllers\Admin;

use Encore\Admin\Grid\Exporters\AbstractExporter;

class EnrollmentsExporter extends AbstractExporter
{
    /**
     * {@inheritdoc}
     */
    public function export()
    {
        $filename = $this->getTable().'.csv';

        $headers = [
            'Content-Encoding'    => 'UTF-8',
            'Content-Type'        => 'text/csv;charset=gbk',
            'Content-Disposition' => "attachment; filename=\"$filename\"",
        ];

        response()->stream(function () {
            $handle = fopen('php://output', 'w');
            //echo chr(0xEF).chr(0xBB).chr(0xBF);
            fwrite($handle, chr(0xEF).chr(0xBB).chr(0xBF));
            $titles = $this->convert_array(['ID', '活动', '姓名', '电话', '公司', '推荐人', '支付状态', '报名时间']);
            fputcsv($handle, $titles);

            $this->chunk(function ($records) use ($handle, &$titles) {

                foreach ($records as $record) {
                    $data = $this->getFormattedRecord($record,[
                       'id',
                        'activity.title',
                        'name',
                        'mobile',
                        'company',
                        'recommender',
                        function($record) {
                            return $record->pay_status?'已支付':'未支付';
                        },
                        'created_at'
                    ]);
                    fputcsv($handle, $data);
                }
            });

            // Close the output stream
            fclose($handle);
        }, 200, $headers)->send();

        exit;
    }

    public function getFormattedRecord($record, $columns=[])
    {
        $data = [];
        foreach ($columns as $column)
        {
            if (is_callable($column)) {
                $data[]= $column($record);
            } else {
                $keys = explode('.', $column);
                $data[] = array_reduce($keys, function($v,$key){ return $v->$key; }, $record);
            }
        }
        return $this->convert_array($data);
    }

    public function convert_array($strs) {
        return array_map(function ($str){return iconv("UTF-8","gbk//TRANSLIT",(string)$str);}, $strs);
    }
}
