<?php

namespace App\Jobs\OpenWork\External;

use App\Facades\Servers\Logs\Log;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Servers\DB\DbService;
use App\Models\OpenWork\DownloadTask as TaskModel;
use App\Models\OpenWork\External\User as Model;
use App\Models\OpenWork\External\FollowTag as ExternalFollowTag;
use App\Models\OpenWork\External\TagGroup;
use App\Jobs\OpenWork\External\UserExportDataJobs;
use Illuminate\Support\Facades\Cache;

/**
 * 导出客户数据-下载
 * @author 刘相欣
 * @version 2.0
 * @date 2025-09-09
 */
class NewUserExport implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	protected $taskData;
	protected $Records;

	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	public function __construct(array $taskData)
	{
		$this->taskData = $taskData;
	}

	public function getCorpId()
	{
		return $this->taskData['corpid'] ?? null;
	}

	public function handle()
	{
		// 数据穿透
		$companyId                  = $this->taskData['company_id'];
		// 切换数据库
		(new DbService())->getConnectionNameByCompanyId($companyId);
		// 调用
		try {
			$this->toxls();
		} catch (\Exception $e) {
			$fileId                     = $this->taskData['file_id'];
			$corpid                     = $this->taskData['corpid'];
			$companyId                  = $this->taskData['company_id'];
			//查询下载任务
			(new TaskModel)->query()->where(['file_id' => $fileId, 'corpid' => $corpid])->update(['status' => 2, 'update_time' => time()]);
			Log::error('new_user_export_jobs', $e->getMessage());
		}
		// 返回结果
		return 						0;
	}


	public function toxls()
	{
		$fileId                     = $this->taskData['file_id'];
		$corpid                     = $this->taskData['corpid'];
		$companyId                  = $this->taskData['company_id'];
		$map                        = $this->taskData['map'];
		$tag_ids                     = $this->taskData['tag_ids'];
		$tag_and_ids				 = $this->taskData['tag_and_ids'];
		$fileName					= $this->taskData['file_name'];
		$corp_name 					= $this->taskData['corp_name'];
		$chunkSize					= 1000;
		//查询下载任务
		$TaskModel 					= (new TaskModel);
		// 查询数据
		$taskId						= $TaskModel->query()->where(['file_id' => $fileId, 'corpid' => $corpid])->value('id');
		// // // 如果没有对应的数据
		if (!$taskId)				return 0;
		// 超时时间设置为 30分钟
		set_time_limit(1800);
		// 临时调整内存
		ini_set('memory_limit', '512M');
		// 实例化
		$Model 					    = new Model();
		// 构建基础查询
		$query 						= $Model->query()
			->join('openwork_external_follow', 'openwork_external_follow.external_userid', '=', 'openwork_external.external_userid')
			->join('custom', 'openwork_external.custom_uid', '=', 'custom.uid', 'LEFT')
			->where($map);
		if ($corp_name) {
			$query->where(function ($query) use ($corp_name) {
				$query->where('openwork_external_follow.remark_corp_name', 'like', "%$corp_name%")
					->orWhere('openwork_external.corp_name', 'like', "%$corp_name%");
			});
		}
		// 如果标签存在子查询
		// 写法
		if (!empty($tag_and_ids) && !empty($tag_ids)) {
			// 且查询和或查询都要
			$subQuery = (new ExternalFollowTag)->query()->whereIn('tag_id', $tag_ids)->select('external_userid')->distinct('external_userid');
			// 添加子查询
			$query->whereIn('openwork_external.external_userid', function ($query1) use ($subQuery) {
				$query1->select('external_userid')->fromSub($subQuery, 'sub1');
			});

			$subQuery = (new ExternalFollowTag)->query()->where('corpid', $corpid)->whereIn('tag_id', $tag_and_ids)->groupBy('external_userid')->havingRaw('COUNT(DISTINCT tag_id) = ?', [count($tag_and_ids)])->select('external_userid');
			// $tag_ids
			$query->whereIn('openwork_external.external_userid', function ($query1) use ($subQuery) {
				$query1->select('external_userid')->fromSub($subQuery, 'sub1');
			});
		} else if (!empty($tag_ids)) { //或查询
			// 子查询
			$subQuery = (new ExternalFollowTag)->query()->whereIn('tag_id', $tag_ids)->select('external_userid')->distinct('external_userid');
			// 添加子查询
			$query->whereIn('openwork_external.external_userid', function ($query1) use ($subQuery) {
				$query1->select('external_userid')->fromSub($subQuery, 'sub1');
			});
		} else if (!empty($tag_and_ids)) { //且查询
			// 子查询
			$subQuery = (new ExternalFollowTag)->query()->where('corpid', $corpid)->whereIn('tag_id', $tag_and_ids)->groupBy('external_userid')->havingRaw('COUNT(DISTINCT tag_id) = ?', [count($tag_and_ids)])->select('external_userid');
			// $tag_ids
			$query->whereIn('openwork_external.external_userid', function ($query1) use ($subQuery) {
				$query1->select('external_userid')->fromSub($subQuery, 'sub1');
			});
		}
		// 获取总数
		$query	= $query->orderByDesc('openwork_external_follow.createtime')->select([
			'openwork_external_follow.external_userid',
			'openwork_external.name',
			'openwork_external_follow.remark',
			'openwork_external_follow.description',
			'openwork_external_follow.status',
			'openwork_external.corp_name',
			'openwork_external_follow.remark_corp_name',
			'openwork_external_follow.follow_userid',
			'openwork_external_follow.createtime',
			'openwork_external_follow.remark_mobiles',
			'custom.phone',
			'openwork_external.custom_uid',
		]);
		// 获取标签分组
		$tagGroup 	= (new TagGroup)->query()->pluck('group_name', 'group_id')->toArray();
		// 获取客户ID
		$totle = $query->count();
		$totle_page = intval(ceil($totle / $chunkSize));
		$now_page = 1;
		// 循环数据
		$query->chunk($chunkSize, function ($chunk) use (&$tagGroup, $corpid, $companyId, $fileName, $totle, $taskId, $totle_page, &$now_page) {
			// 转格式
			$chunk					= $chunk->toArray();
			$message_data = [
				'corpid' => $corpid,
				'totle' => $totle,
				'file_name' => $fileName,
				'tagGroup' => $tagGroup,
				'companyId' => $companyId,
				'chunk' => $chunk,
				'taskId' => $taskId,
				'totle_page' => $totle_page,
				'now_page' => $now_page,
			];
			UserExportDataJobs::dispatch($message_data);
			// UserExportDataJobs::dispatchSync($message_data);
			$now_page++;
		});
		return true;
	}
}
