GiftExporter.php 7.6 KB
<?php
/**
+-----------------------------------------------------------------------------------------------------------------------
 * 扩展类:Gift 导出扩展类
+-----------------------------------------------------------------------------------------------------------------------
 *
 * 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\Gift\Gift;
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 GiftExporter
 *
 * @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 GiftExporter 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'           => __('user'),
            'giftable_type'     => __('type'),
            'number'            => __('number'),
            'goods_type'        => __('goods_type'),
            'goods_name'        => __('goods_name'),
            'sku'               => __('goods_specification'),
            'goods_price'       => __('goods_price'),
            'goods_quantity'    => __('goods_quantity'),
            'price'             => __('gift_price'),
            'record_id'         => __('express'),
            'address_id'        => __('收货地址'),
            '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' => 20, 'H' => 10, 'I' => 10,
                    'J' => 10, 'K' => 50, 'L' => 50, 'M' => 50, '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 =  Gift::with(['user','giftable','exchangeGoods','express','address'])
            ->when($para = request('number'), function ($query) use ($para) {
                $query->where('number', 'LIKE', "%$para%");
            })
            ->when($para = request('goods_type'), function ($query) use ($para) {
                $query->where('goods_type', $para);
            })
            ->when($para = request('status', 0), function ($query) use ($para) {
                $query->where('status', $para);
            })
            ->when($para = request('giftable_type'), function ($query) use ($para) {
                $query->where('giftable_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);
            $express = $item->express;
            $express_str = '--';
            if ($express) {
                $express_str = "物流公司: $express->company_name, 物流单号: $express->express_no";
            }
            $address = $item->address;
            $full_address = '';
            if ($address) {
                $full_address = "$address->name, $address->mobile, $address->full_address";
            }

            return [
                $index+1,
                $user->nickname .','. $user->mobile,
                $item->type_show,
                "\t".$item->number,
                $item->goods_type_show,
                $item->goods_name,
                $item->sku_name,
                $item->goods_price,
                $item->goods_quantity,
                $item->price,
                $express_str,
                $full_address,
                $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');
    }
}