<?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\SpecifyTagJobs;
use App\Models\Company\Tag\Tags as CompanyTagsModel;
use App\Facades\Servers\Wechat\OpenWork;
use App\Servers\OpenWork\External\CorpTagGroupService;
use App\Models\Company\Corp\TagRelation as TagRelationModel;


/**
 * 商户指定企微标签组队列
 * @author  唐远望
 * @version  1.0
 * @date   2025-09-22
 */
class SpecifyTagGroupJobs 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();
            $CompanyTagsModel = new CompanyTagsModel();
            $TagRelationModel = new TagRelationModel();
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $companyId . '_CompanySyncSpecifyTagGroupJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $corpid = $this->message_data['corpid'];
            $company_tag_group_id = $this->message_data['company_tag_group_id'];
            $company_tag_ids = $this->message_data['company_tag_ids'];
            //查询所有SASS标签组名称
            $sass_tag_group_data = $GroupModel->where('company_id', $companyId)->where('id', $company_tag_group_id)->first();
            $TagGroupModel = $TagGroupModel->query()->where('group_name', $sass_tag_group_data->group_name);
            //获取企微标签组列表
            $tagGroup_data = $TagGroupModel->get(['id', 'group_name', 'group_id'])->first();
            if (!$tagGroup_data) {
                //差异部分执行标签组新增
                $tags_where = ['company_id' => $companyId, 'group_id' => $company_tag_group_id];
                $sass_tag_names = $CompanyTagsModel->where($tags_where)->whereIn('id', $company_tag_ids)->pluck('tag_name')->toarray();
                if (empty($sass_tag_names)) {
                    Log::info('job_error', '商户同步指定企微标签失败-标签列表未找到', ['data' => $tags_where, 'tag_id' => $company_tag_ids]);
                    return true;
                }
                $data['tag'] = [];
                foreach ($sass_tag_names as $key => $value) {
                    $data['tag'][$key]['name'] = $value;
                    $data['tag'][$key]['order'] = 0;
                }
                $data['group_name'] = $sass_tag_group_data->group_name;
                // 获取实例
                $work               = OpenWork::getWork($corpid);
                // 数据结果
                $result             = $work->external_contact->addCorpTag($data);
                // 如果获取结果失败
                if (!$result) {
                    Log::info('job_error', '商户同步指定企微标签新增同步失败', ['data' => $data]);
                    return true;
                }
                // 错误提示
                if ($result['errcode']) {
                    Log::info('job_error', '商户同步指定企微标签新增同步失败', ['data' => OpenWork::getErrmsg($result['errcode'])]);
                    return true;
                }
                $tag_group = $result['tag_group'];
                $insert_tag_group_relation_data = [
                    'company_id' => $companyId,
                    'sass_group_id' => $company_tag_group_id,
                    'scrm_group_id' => $tag_group['group_id'],
                    'insert_time' => time(),
                ];
                $TagGroupRelationModel->insert($insert_tag_group_relation_data);
                $tag_list = $tag_group['tag'];
                foreach ($tag_list as $key => $value) {
                    $tag_where = ['company_id' => $companyId, 'group_id' => $company_tag_group_id, 'tag_name' => $value['name']];
                    $CompanyTagData = $CompanyTagsModel->where($tag_where)->first();
                    if (!$CompanyTagData) {
                        Log::info('job_error', '商户同步指定企微标签失败-标签未找到', ['data' => $tag_where]);
                        return true;
                    }
                    $insert_tag_relation_data = [
                        'company_id' => $companyId,
                        'sass_group_id' => $company_tag_group_id,
                        'scrm_group_id' => $tag_group['group_id'],
                        'sass_tag_id' => $CompanyTagData->id,
                        'scrm_tag_id' => $value['id'],
                        'insert_time' => time(),
                    ];
                    $TagRelationModel->insert($insert_tag_relation_data);
                }
                $this->sync_get_list($corpid);
            }else{
                $group_data = $tagGroup_data->toarray();
                $wechat_group_id = $group_data['group_id'];
                //判断是否已同步
                $tagGroupRelation_info = $TagGroupRelationModel->where(['company_id' => $companyId, 'scrm_group_id' => $wechat_group_id])->first();
                if ($tagGroupRelation_info) {
                    //创建标签同步任务
                    $message_data = [
                        'company_id' => $companyId,
                        'corpid' => $corpid,
                        'scrm_group_id' => $tagGroupRelation_info->scrm_group_id,
                        'sass_group_id' => $tagGroupRelation_info->sass_group_id,
                        'company_tag_ids' => $company_tag_ids,
                    ];
                    SpecifyTagJobs::dispatch($message_data);
                    // SpecifyTagJobs::dispatchSync($message_data);
                    return true;
                }
                //查询本地是否已存在该标签组
                $tag_group_name = $GroupModel->where('company_id', $companyId)->where('group_name', $group_data['group_name'])->first();
                if (!$tag_group_name) {
                    Log::info('job_error', '商户同步指定企微标签失败-标签组信息不存在', ['data' => $group_data['group_name']]);
                    return true;
                }
                $company_tag_group_id = $tag_group_name->id;
                $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,
                    'company_tag_ids' => $company_tag_ids,
                ];
                // SpecifyTagJobs::dispatch($message_data);
                SpecifyTagJobs::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()]);
        }
    }

    /**
     * 同步标签列表  /openwork/external_tag/sync_get_list
     * @author 唐远望
     * @version 1.0
     * @date 2025-09-23
     *
     */
    public function sync_get_list($authCorpId)
    {
        // 获取实例
        $work           = OpenWork::getWork($authCorpId);
        // 数据结果
        $result         = $work->external_contact->getCorpTags();
        // 如果获取结果失败
        if (!$result) {
            Log::info('job_error', '商户同步指定企微标签组-获取失败企微接口失败', []);
        }
        // 错误提示
        if ($result['errcode']) return json_send(['code' => 'error', 'msg' => OpenWork::getErrmsg($result['errcode'])]);
        (new CorpTagGroupService())->handle_corp_group_tag($authCorpId, $result['tag_group']);
    }

    /**
     * 队列完全失败处理  
     * @author 唐远望
     * @version 1.0
     * @date 2025-09-23
     *
     */
    public function failed(\Throwable $exception)
    {
        Log::info('job_error', '商户同步指定企微标签组队列执行失败', ['data' => $this->message_data, 'error' => $exception]);
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
