<?php

namespace App\Jobs\Company\Corp;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Facades\Servers\Logs\Log;
use App\Servers\DB\DbService;
use App\Models\OpenWork\job\Records;
use App\Models\Manager\CustomExternal;
use App\Jobs\Company\Corp\ExternalTagJobs;
use App\Models\Company\Custom\Tag as CustomTagModel;

/**
 * 商户同步客户标签-外部联系人客服
 * @author  唐远望
 * @version  1.0
 * @date   2025-09-23
 */
class CustomerTagJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $message_data;
    protected $Records;

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

    /**
     * Execute the job.
     * 如果本地已同步的企微标签数量等于企微标签数量，则更新任务记录为成功
     * 标签上限  （https://developer.work.weixin.qq.com/document/path/92696#%E6%B7%BB%E5%8A%A0%E4%BC%81%E4%B8%9A%E5%AE%A2%E6%88%B7%E6%A0%87%E7%AD%BE）
     * 每个企业最多可配置10000个企业标签
     * 注：标签的节点可以是一个部门或一个人。
     * @return void
     */
    public function handle()
    {
        try {
            $companyId = $this->message_data['company_id'];
            (new DbService())->getConnectionNameByCompanyId($companyId);
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $companyId . '_CompanySyncSpecifyTagJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $CustomExternal = new CustomExternal();
            $CustomTagModel = new CustomTagModel();
            $corpid = $this->message_data['corpid'];
            $external_userid = $this->message_data['external_userid'];
            $local_tags_data = $this->message_data['local_tags_data'];
            $page = $this->message_data['page'];
            $perPage = $this->message_data['perPage'];
            //获取已经添加客服的外部联系人，每次取500个
            $externalUser_query =  $CustomExternal->where('corpid', $corpid)->where('status', 1);
            if ($external_userid) {
                $external_userid_array = explode(',', $external_userid);
                $external_userid = array_filter($external_userid_array); //移除数组内空的字符
                $externalUser_query = $externalUser_query->whereIn('external_userid', $external_userid);
            }
            //分页查询数据
            $externalUser_data = $externalUser_query->get(['id', 'custom_uid', 'external_userid'])->skip(($page - 1) * $perPage)->take($perPage)->toarray();
            if (empty($externalUser_data)) {
                $this->Records->delete();
                return true;
            }
            //查询本地用户标签
            $custom_uid_array = array_column($externalUser_data, 'custom_uid');
            $local_user_tag_data = $CustomTagModel->where('company_id', $companyId)->whereIn('custom_uid',$custom_uid_array)->get()->groupBy('custom_uid')->map(function ($items) {
                return $items->pluck('tag_id')->implode(',');
            })->toArray();
            
            if (!empty($local_user_tag_data)) {
                foreach ($local_user_tag_data as $local_custom_uid =>  $local_tag_id) {
                    $local_user_tag_data[$local_custom_uid] = explode(',', $local_tag_id);
                }
            }
            $message_data = [
                'company_id' => $companyId,
                'corpid' => $corpid,
                'external_user_data' => $externalUser_data,
                'local_user_tag_data' => $local_user_tag_data,
                'local_tags_data' => $local_tags_data,
            ];
            ExternalTagJobs::dispatch($message_data);
            // ExternalTagJobs::dispatchSync($message_data);
            //继续执行下一页
            $message_data = [
                'company_id' => $companyId,
                'corpid' => $corpid,
                'external_userid' =>!empty($external_userid) ? implode(',',$external_userid):'',
                'local_user_tag_data' => $local_user_tag_data,
                'local_tags_data' => $local_tags_data,
                'page' => $page + 1,
                'perPage' => $perPage,
            ];
            CustomerTagJobs::dispatch($message_data);
            //删除任务记录
            if ($this->Records) {
                $this->Records->delete();
            }
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', '商户同步客户标签队列-外部联系人客服同步失败', ['data' => $this->message_data, 'error' => $e->getMessage()]);
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', '商户同步客户标签队列-外部联系人客服执行失败', ['data' => $this->message_data, 'error' => $exception->getMessage()]);

        // 只有在Records存在时才删除
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
