<?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\Member\Models\MemberExtend;
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 MemberImport implements ShouldQueue {
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	protected $file;
	protected $tasks;

	/**
	 * Create a new job instance.
	 */
	public function __construct($file, Tasks $tasks) {
		$this->file = Storage::disk('public')->path($file);
		$this->tasks = $tasks;
	}

	/**
	 * Execute the job.
	 */
	public function handle(): void {
		//扩展字段
		$fields = Fields::all();
		Excel::import($this->file)->each(function (SheetInterface $sheet) use($fields) {
			$chunkSize = 100;
			$sheet->chunk($chunkSize, function (SheetCollection $collection) {
				$collection->each(function ($row) {
					if (empty($row)){
						$this->tasks->status = 1;
						$this->tasks->save();
						return true;
					}

					$member = Member::updateOrCreate([
						'username' => $row['用户名'],
						'mobile' => $row['手机号'],
						'email' => $row['邮箱']
					], [
						'nickname' => $row['昵称'],
						'password' => $row['手机号'],
					]);

					if ($member->id) {
						if($member->extend()->exists()){
							$extend = $member->extend()->first();
						}else{
							$extend = new MemberExtend();
							$extend->member_id = $member->id;
						}
						foreach ($fields as $field) {
							$extend->{$field->name} = $row[$field->title];
						}
					}
				});
			});
		});
	}
}