<?php
<?php

/**
 * 导出示例
 * $data = [
 * '服务名称' => 'cate_name',
 * '规格' => 'suk_unique',
 * '金额' => 'pay_price',
 * '订单状态' => 'status_name',
 * '客户昵称' => 'nickname',
 * '客户电话' => 'phone',
 * '客户下单电话' => 'user_phone',
 * '师傅名称' => 'service_nickname',
 * '师傅电话' => 'service_phone',
 * '服务地址' => 'user_address',
 * '服务时间' => 'service_day_time',
 * ];
 * ExcelExport::export($sql, '服务订单', $data);
 */

namespace app\core\util;

use think\Db;

trait ExcelExport
{
    public static function export($sql, $filename = 'export', $data = [])
    {
        $file_name = $filename . time() . ".csv";

        $fields = '';
        $title_fields = [];
        $temp_key = 0;
        $fields_count = count($data);

        foreach ($data as $key => $field) {
            $temp_key += 1;
            $fields .= "ifnull({$field},'') as {$field}" . ($temp_key < $fields_count ? ',' : '');
            $title_fields[] = $key;
        }

        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . $file_name);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码,防止乱码
        fputcsv($fp, $title_fields);//插入标题
        foreach (self::sqlQuery("SELECT {$fields} FROM ({$sql}) as t") as $key => $value) {
            //去除数字科学计数法
            $value = array_map(function ($item) {
                if (is_numeric($item)) {
                    return "\t" . $item;
                }
                return $item;
            }, $value);

            fputcsv($fp, $value);
        }
        fclose($fp);
    }

    private static function sqlQuery($sql)
    {
        foreach (Db::query($sql) as $key => $val) {
            yield $val;
        }
    }

}