<?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;
use App\Facades\Servers\Wechat\OpenWork;
use Illuminate\Support\Facades\DB;

/**
 * 商户指定企微标签队列
 * @author  唐远望
 * @version  1.0
 * @date   2025-09-22
 */
class SpecifyTagJobs 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()
    {
        DB::beginTransaction();
        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 . '_CompanySyncSpecifyTagJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $corpid = $this->message_data['corpid'];
            $company_tag_ids = $this->message_data['company_tag_ids'];
            $scrm_group_id = $this->message_data['scrm_group_id'];
            $company_tag_group_id = $this->message_data['sass_group_id'];
            //查询所有SASS标签名称
            $sass_tag_data = $CompanyTagsModel->where('company_id', $companyId)->where(['group_id' => $company_tag_group_id])->whereIn('id', $company_tag_ids)->get(['id', 'tag_name'])->toarray();
            if(empty($sass_tag_data)){
                Log::info('job_error', '商户同步指定企微标签队列同步失败-本地标签未找到', ['data' => $this->message_data]);
                return false;
            }
            $sass_tag_names = array_column($sass_tag_data, 'tag_name');
            //获取企微标签列表
            $tag_datas = $WechatTagModel->where('corpid', $corpid)->where(['group_id' => $scrm_group_id])->whereIn('tag_name', $sass_tag_names)->get(['id', 'tag_name', 'tag_id'])->toarray();
            //获取本地已同步的企微标签列表
            $tagRelationList = $TagRelationModel->where('company_id', $companyId)->pluck('scrm_tag_id')->toarray();
            if (!empty($tag_datas)) {
                foreach ($tag_datas as $tag_data) {
                    $wechat_tag_id = $tag_data['tag_id'];
                    //判断是否已同步
                    if (in_array($wechat_tag_id, $tagRelationList)) {
                        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) {
                        continue;
                    }
                    $company_tag_id = $tag_name_data->id;
                    $insert_tag_relation_data = [
                        'company_id' => $companyId,
                        'sass_group_id' => $company_tag_group_id,
                        'scrm_group_id' => $scrm_group_id,
                        'sass_tag_id' => $company_tag_id,
                        'scrm_tag_id' => $wechat_tag_id,
                        'insert_time' => time(),
                    ];
                    $TagRelationModel->insert($insert_tag_relation_data);
                }
            } else {
                foreach ($sass_tag_names as $key => $value) {
                    $data['tag'][$key]['name'] = $value;
                    $data['tag'][$key]['order'] = 0;
                }
                $data['group_id'] = $scrm_group_id;
                // 获取实例
                $work               = OpenWork::getWork($corpid);
                // 数据结果
                $result             = $work->external_contact->addCorpTag($data);
                // 如果获取结果失败
                if (!$result) {
                    Log::info('job_error', '商户同步指定企微标签到SCRM新增同步失败-执行添加失败', ['data' => $data]);
                    return true;
                }
                $insert_time = time();
                $insert_tag_relation_data = [];
                $insert_scrm_tag_data = [];
                if (!isset($result['tag_group']) || !isset($result['tag_group']['tag'])) {
                    Log::info('job_error', '商户同步指定企微标签到SCRM新增同步失败-新增标签数据为空', ['data' => $data]);
                    return true;
                }
                $result_tag_data = $result['tag_group']['tag'];
                if (!empty($result_tag_data)) {
                    foreach ($result_tag_data as $key => $value) {
                        $tag_name = $value['name'];
                        $scrm_tag_id = $value['id'];
                        $insert_scrm_tag_data[] = [
                            'corpid' => $corpid,
                            'tag_id' => $scrm_tag_id,
                            'tag_name' => $tag_name,
                            'order' => '0',
                            'status' => '0',
                            'group_id' => $scrm_group_id,
                            'insert_time' => $insert_time,
                            'update_time' => $insert_time,
                        ];
                        foreach ($sass_tag_data as $key => $value) {
                            if ($value['tag_name'] == $tag_name) {
                                //添加标签映射关系
                                $insert_tag_relation_data[] = [
                                    'company_id' => $companyId,
                                    'scrm_group_id' => $scrm_group_id,
                                    'sass_group_id' => $company_tag_group_id,
                                    'scrm_tag_id' => $scrm_tag_id,
                                    'sass_tag_id' => $value['id'],
                                    'insert_time' => $insert_time,
                                ];
                            }
                        }
                    }
                }
                if(!empty($insert_scrm_tag_data)){
                    $WechatTagModel->insert($insert_scrm_tag_data);
                }
                if(!empty($insert_tag_relation_data)){
                     $TagRelationModel->insert($insert_tag_relation_data);
                }
            }
            DB::commit();
            //删除任务记录
            if ($this->Records) {
                $this->Records->delete();
            }
        } catch (\Exception $e) {
             DB::rollBack();
            // 失败处理...
            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();
        }
    }
}
