<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace Modules\Member\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Modules\Member\Models\Member;
use Modules\Member\Models\Fields;
use Modules\System\Models\Tasks;
use Illuminate\Support\Facades\Storage;
use Dcat\EasyExcel\Excel;
use Dcat\EasyExcel\Contracts\Sheet as SheetInterface;
use Dcat\EasyExcel\Support\SheetCollection;

class MemberExport implements ShouldQueue {
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	protected $params;
	protected $tasks;

    /**
     * Create a new job instance.
     */
    public function __construct($params, Tasks $tasks) {
		$this->params = $params;
		$this->tasks = $tasks;
    }

    /**
     * Execute the job.
     */
    public function handle(): void {
		$file = $this->params['fileName'] ? 'export/' . $this->params['fileName'] : 'member_' . date('YmdHis') . '.xlsx';

		//扩展字段
		$fields = Fields::all();
		Excel::export()->chunk(function(int $page) use($fields){
			$chunkSize = 1000;
			$query = Member::with(['extend', 'level'])->forPage($page, $chunkSize);
			logger($query->toSql());
			if ($query->count() == 0) {
				$this->tasks->status = 1;
				$this->tasks->save();
				return;
			}
			$data = $query->get();
			$exportData = [];
			foreach ($data as $key => $value) {
				$item = [
					'用户名' => $value->username,
					'昵称' => $value->nickname,
					'手机号' => $value->mobile,
					'邮箱' => $value->email,
				];
				foreach ($fields as $field) {
					$item[$field->title] = $value->extend ? $value->extend->{$field->name} : '';
				}
				$item['等级'] = $value->level ? $value->level->title : '未设置等级';
				$item['等级到期时间'] = $value->level_expire_time;
				$item['登录次数'] = $value->login_count;
				$item['注册时间'] = $value->created_at;

				$exportData[] = $item;
			}
			return $exportData;
		})->disk(Storage::disk('public'))->store($file);
    }
}