<?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\Tag as WechatTagModel;
use App\Models\Company\Corp\TagRelation as TagRelationModel;
use App\Models\Company\Tag\Tags as CompanyTagsModel;

/**
 * 商户企微标签队列
 * @author  唐远望
 * @version  1.0
 * @date   2025-09-22
 */
class TagJobs 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);
            $TagRelationModel = new TagRelationModel();
            $WechatTagModel = new WechatTagModel();
            $CompanyTagsModel = new CompanyTagsModel();
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $companyId . '_CompanySyncTagJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $corpid = $this->message_data['corpid'];
            $wechat_group_id = $this->message_data['scrm_group_id'];
            $company_tag_group_id = $this->message_data['sass_group_id'];
            //获取企微标签列表
            $tag_datas = $WechatTagModel->where('corpid', $corpid)->where(['group_id' => $wechat_group_id])->get(['id', 'tag_name', 'tag_id'])->toarray();
            //获取本地已同步的企微标签列表
            if (!empty($tag_datas)) {
                foreach ($tag_datas as $tag_data) {
                    $wechat_tag_id = $tag_data['tag_id'];
                    $tagRelationinfo = $TagRelationModel->where('company_id', $companyId)->where(['sass_group_id'=>$company_tag_group_id,'scrm_group_id'=>$wechat_group_id])->where('scrm_tag_id',$wechat_tag_id)->first();
                    //判断是否已同步
                    if ($tagRelationinfo) {
                        $tag_name_data = $CompanyTagsModel->where('company_id', $companyId)->where('group_id',$company_tag_group_id)->where('id', $tagRelationinfo->sass_tag_id)->first();
                        if($tag_name_data){
                            $tag_name_data->tag_name = $tag_data['tag_name'];
                            $tag_name_data->update_time = time();
                            $tag_name_data->save();
                        }
                        continue;
                    }
                    //查询本地是否已存在该标签
                    $tag_name_data = $CompanyTagsModel->where('company_id', $companyId)->where('group_id',$company_tag_group_id)->where('tag_name', $tag_data['tag_name'])->first();
                    if ($tag_name_data) {
                        $company_tag_id = $tag_name_data->id;
                    } else {
                        $insert_tag_group_data = [
                            'company_id' => $companyId,
                            'tag_name' => $tag_data['tag_name'],
                            'group_id' => $company_tag_group_id,
                            'order' => '0',
                            'status' => '1',
                            'type' => '1',
                            'insert_time' => time(),
                        ];
                        //添加本地标签信息
                        $company_tag_id = $CompanyTagsModel->insertGetId($insert_tag_group_data);
                    }
                    $insert_tag_relation_data = [
                        'sass_group_id' => $company_tag_group_id,
                        'scrm_group_id' => $wechat_group_id,
                        'company_id' => $companyId,
                        'sass_tag_id' => $company_tag_id,
                        'scrm_tag_id' => $wechat_tag_id,
                        'insert_time' => time(),
                    ];
                    $TagRelationModel->insert($insert_tag_relation_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();
        }
    }
}
