OrderExporter.php 8.3 KB
<?php
/**
+-----------------------------------------------------------------------------------------------------------------------
 * 扩展类:Order 导出扩展类
+-----------------------------------------------------------------------------------------------------------------------
 *
 * PHP version 7
 *
 * @category  App\Admin\Extensions\Exporter
 * @package   App\Admin\Extensions\Exporter
 * @author    Richer <yangzi1028@163.com>
 * @date      2022年7月29日13:54:24
 * @copyright 2020-2022 Richer (http://www.xxxxxx.com)
 * @license   http://www.xxxxxx.com License
 * @link      http://www.xxxxxx.com
 */
namespace App\Admin\Extensions\Exporter;

use App\Models\Order\Order;
use Illuminate\Support\Arr;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Facades\Excel;

/**
 * Class OrderExporter
 *
 * @category  App\Admin\Extensions\Exporter
 * @package   App\Admin\Extensions\Exporter
 * @author    Richer <yangzi1028@163.com>
 * @date      2022年7月29日13:54:24
 * @copyright 2020-2022 Richer (http://www.xxxxxx.com)
 * @license   http://www.xxxxxx.com License
 * @link      http://www.xxxxxx.com
 */
class OrderExporter implements FromCollection, WithEvents, WithStrictNullComparison, WithColumnFormatting
{
    // 要导出的数据
    public $data;
    // 总行数
    public $rowNum;
    // 标题
    public $title;
    // 查询
    public $query = 'all';
    // 导出列表
    protected $columns = [];

    /**
     * 构造函数
     *
     * ClassExporter constructor.
     * @param $excel_title
     * @param string $query
     */
    public function __construct($excel_title, $query = 'all')
    {
        $this->columns = $this->getColumns();
        $this->title = $excel_title;
        $this->query = $query;
    }

    /**
     * 生效列表
     *
     * @return array
     */
    public function getColumns()
    {
        return [
            'id'                => __('No'),
            'user_id'           => __('ordered_by'),
            'primary_distributor_id'  => __('primary_distributor'),
            'secondary_distributor_id'  => __('secondary_distributor'),
            'orderable_type'    => __('type'),
            'goods_name'        => __('goods_name'),
//            'goods_image'       => __('goods_image'),
            'goods_price'       => __('goods_price'),
            'number'            => __('order_number'),
            'quantity'          => __('quantity'),
            'total_amount'      => __('total_amount'),
            'total_points'      => __('total_points'),
            'points_deducted'   => __('points_deducted'),
            'points_deducted_amount'    => __('points_deducted_amount'),
            'points_deduct_rate'    => __('points_deduct_rate'),
            'points_deduct_limit'      => __('points_deduct_limit'),
            'payment_amount'  => __('payment_amount'),
            'paid_at'  => __('paid_at'),
            'paid_type'  => __('paid_type'),
            'remark'  => __('remark'),
            'status'       => __('status'),
            'created_at'       => __('created_at'),
        ];
    }

    /**
     * registerEvents.
     * 事件监听
     * @return array
     */
    public function registerEvents(): array
    {
        return [
            // 生成表单元后处理事件
            AfterSheet::class => function (AfterSheet $event) {
                // 定义列宽度
                $widths = [
                    'A' => 5, 'B' => 20, 'C' => 20, 'D' => 20, 'E' => 15, 'F' => 50, 'G' => 50, 'H' => 10, 'I' => 20,
                    'J' => 5, 'K' => 10, 'L' => 10, 'M' => 10, 'N' => 15, 'O' => 15, 'P' => 15, 'Q' => 15, 'R' => 18,
                    'S' => 15, 'T' => 50, 'U' => 10, 'V' => 15
                ];

                foreach ($widths as $k => $v) {
                    // 设置列宽度
                    $event->sheet->getDelegate()->getColumnDimension($k)->setWidth($v);
                }

                // 设置表头样式
                $event->sheet->getDelegate()->getStyle('A1:Z1')->applyFromArray([
                    // 设置单元格字体
                    'font' => [
                        'name'  => '宋体',
                        'bold'  => true,
                        'italic' => false,
                        'strikethrough' => false,
                        'color' => [
                            'rgb' => '000000',
                        ],
                    ],
                    // 设置单元格背景色
//                    'fill' => [
//                        'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
//                        'rotation' => 0, //渐变角度
//                        'startColor' => [
//                            'rgb' => 'FEFF00' //初始颜色
//                        ],
//                        'endColor' => [
//                            'argb' => 'FEFF00',
//                        ],
//                    ],
                ]);
            },
        ];
    }

    /**
     * collection.
     *
     * @return \Illuminate\Support\Collection
     *
     * @throws \Exception
     */
    public function collection()
    {
        ini_set("memory_limit", "-1");

        $query =  Order::with(['user','primaryDistributor','secondaryDistributor'])
            ->when($para = request('goods_name'), function ($query) use ($para) {
                $query->where('goods_name', 'LIKE', "%$para%");
            })
            ->when($para = request('number'), function ($query) use ($para) {
                $query->where('number', 'LIKE', "%$para%");
            })
            ->when($para = request('paid_type', 0), function ($query) use ($para) {
                $query->where('paid_type', $para);
            })
            ->when($para = request('status', 0), function ($query) use ($para) {
                $query->where('status', $para);
            })
            ->when($para = request('orderable_type', 0), function ($query) use ($para) {
                $query->where('orderable_type', $para);
            })
            ->when($para = request('created_at'), function ($query) use ($para) {
                $query->whereDate('created_at', '>=', Arr::get($para, 'start'))
                    ->whereDate('created_at', '<=', Arr::get($para, 'end'));
            });
        $list =  $query->latest()->get();

        $data = $list->map(function ($item, $index) {
            $user = optional($item->user);
            $user2 = $item->primaryDistributor;
            $user3 = $item->secondaryDistributor;
            return [
                $index+1,
                $user->nickname .','. $user->mobile,
                $user2 ? $user2->nickname .','. $user2->mobile : '--',
                $user3 ? $user3->nickname .','. $user3->mobile : '--',
                $item->type_show,
                $item->goods_name,
//                $item->goods_image,
                $item->goods_price,
                "\t".$item->number,
                $item->quantity,
                $item->total_amount,
                $item->total_points,
                $item->points_deducted,
                $item->points_deducted_amount,
                $item->points_deduct_rate > 0 ? $item->points_deduct_rate * 100 .'%' : '--',
                $item->points_deduct_limit > 0 ? $item->points_deduct_limit * 100 .'%' : '--',
                $item->payment_amount,
                format_date($item->paid_at),
                $item->paid_type_show,
                $item->remark,
                $item->status_show,
                format_date($item->created_at) ?? '--',
            ];
        })->toArray();

        // 设置表头
        $headings = array_values($this->columns);
        array_unshift($data, $headings);
        $this->rowNum = count($data);
        // 此处数据需要数组转集合
        return collect($data);
    }

    /**
     * @return array
     */
    public function array(): array
    {
//

        return [];
    }

    /**
     * 设置列单元格格式
     */
    public function columnFormats(): array
    {
        // TODO: Implement columnFormats() method.
        return [

        ];
    }

    public function export()
    {
        return Excel::download($this, $this->title.'列表_'.date('YmdHis') . '.xlsx');
    }
}