<?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\Company\Corp\TagGroup as TagGroupModel;
use App\Models\Company\Corp\TagGroupRelation as TagGroupRelationModel;
use App\Models\Company\Tag\Group as GroupModel;
use App\Jobs\Company\Corp\TagJobs;

/**
 * 商户企微标签组队列
 * @author  唐远望
 * @version  1.0
 * @date   2025-09-22
 */
class TagGroupJobs 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);
            $TagGroupRelationModel = new TagGroupRelationModel();
            $TagGroupModel = new TagGroupModel();
            $GroupModel = new GroupModel();
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $companyId . '_CompanySyncTagGroupJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $corpid = $this->message_data['corpid'];
            $TagGroupModel = $TagGroupModel->query();
            //获取企微标签组列表
            $tagGroup_data = $TagGroupModel->get(['id', 'group_name', 'group_id'])->toarray();
            if (!empty($tagGroup_data)) {
                foreach ($tagGroup_data as $group_data) {
                    $wechat_group_id = $group_data['group_id'];
                    //判断是否已同步
                    $tagGroupRelation_info = $TagGroupRelationModel->where(['company_id' => $companyId, 'scrm_group_id' => $wechat_group_id])->first();
                    if ($tagGroupRelation_info) {
                        $tag_group_data = $GroupModel->where('company_id', $companyId)->where('id', $tagGroupRelation_info->sass_group_id)->first();
                        if ($tag_group_data) {
                            $tag_group_data->group_name = $group_data['group_name'];
                            $tag_group_data->update_time = time();
                            $tag_group_data->save();
                        }
                        //创建标签同步任务
                        $message_data = [
                            'company_id' => $companyId,
                            'corpid' => $corpid,
                            'scrm_group_id' => $tagGroupRelation_info->scrm_group_id,
                            'sass_group_id' => $tagGroupRelation_info->sass_group_id,
                        ];
                        TagJobs::dispatch($message_data);
                        // TagJobs::dispatchSync($message_data);
                        continue;
                    }
                    //查询本地是否已存在该标签组
                    $tag_group_name = $GroupModel->where('company_id', $companyId)->where('group_name', $group_data['group_name'])->first();
                    if ($tag_group_name) {
                        $company_tag_group_id = $tag_group_name->id;
                    } else {
                        $insert_tag_group_data = [
                            'company_id' => $companyId,
                            'group_name' => $group_data['group_name'],
                            'order' => '0',
                            'status' => '1',
                            'type' => '1',
                            'insert_time' => time(),
                        ];
                        //添加本地标签组信息
                        $company_tag_group_id = $GroupModel->insertGetId($insert_tag_group_data);
                    }
                    $insert_tag_group_relation_data = [
                        'company_id' => $companyId,
                        'sass_group_id' => $company_tag_group_id,
                        'scrm_group_id' => $wechat_group_id,
                        'insert_time' => time(),
                    ];
                    $TagGroupRelationModel->insert($insert_tag_group_relation_data);
                    $message_data = [
                        'company_id' => $companyId,
                        'corpid' => $corpid,
                        'scrm_group_id' => $wechat_group_id,
                        'sass_group_id' => $company_tag_group_id,
                    ];
                    TagJobs::dispatch($message_data);
                    // TagJobs::dispatchSync($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]);
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
