<?php

namespace App\Jobs\OpenWork\External;

use App\Servers\DB\DbService;
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\Models\OpenWork\job\Records;
use App\Models\OpenWork\Contactway\Qrcode;
use App\Facades\Servers\Wechat\OpenWork;
use App\Models\OpenWork\External\Tag as TagModel;
use App\Models\OpenWork\External\User as UserModel;
use App\Models\Manager\CustomExternal;
use App\Servers\OpenWork\External\ContactService;
use App\Models\OpenWork\External\FollowTag as FollowTagModel;
use App\Servers\OpenWork\External\TagLogService;
use App\Models\OpenWork\External\Follow as FollowModel;

/**
 * 更新用户标签队列
 * @author    唐远望
 * @version   1.0
 * @date      2025-11-12
 * 
 */
class UpdateUserTagJobs 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.
     *
     * @return void
     */
    public function handle()
    {

        try {
            $corpid = $this->message_data['corpid'];
            (new DbService())->getConnectionNameByCorpId($corpid);
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $corpid . '_UpdateUserTagJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);

            $TagLogService = new TagLogService();
            $UserModel = new UserModel();
            $FollowTagModel = new FollowTagModel();
            $FollowModel = new FollowModel();
            $userid = $this->message_data['userid'];
            $external_userid = $this->message_data['external_userid'];
            $state = $this->message_data['state'];

            $work  = OpenWork::getWork($corpid);
            if ($state) {
                //执行打标签业务
                $this->channel_qrcode_tag($work, $userid, $external_userid, $state);
            }
            // 获取外部联系人的详情
            $extUser                    = $work->external_contact->get($external_userid);
            if (!$extUser || $extUser['errcode']) {
                Log::info('job_error', 'UpdateUserTagJobs获取外部人详情错误：', ['data' => $external_userid, 'error' => $extUser]);
                $this->Records->delete();
                return true;
            }
            // 是否已经有该用户
            $oldId = $UserModel->where([['external_userid', '=', $external_userid], ['corpid', '=', $corpid]])->value('id');
            // 组合写入数据
            $external                    = [
                'corpid' => $corpid,
                'external_userid' => $external_userid,
                'name' => $extUser['external_contact']['name'],
                'type' => $extUser['external_contact']['type'],
                'gender' => $extUser['external_contact']['gender'],
                'status' => 0,
                'position' => isset($extUser['external_contact']['position']) ? $extUser['external_contact']['position'] : '',
                'corp_name' => isset($extUser['external_contact']['corp_name']) ? $extUser['external_contact']['corp_name'] : '',
                'update_time' => time()
            ];
            // 新增时间
            if (!$oldId)                $external['insert_time'] = time();
            // 写入数据表
            $external['id'] = $oldId ? $UserModel->where([['id', '=', $oldId]])->update($external) : $UserModel->insertGetId($external);
            // 如果写入失败
            if (!$external['id']) {
                Log::info('job_error', 'UpdateUserTagJobs用户写入失败', ['data' => $external]);
                $this->Records->delete();
                return true;
            }
            //绑定用户关系
            (new CustomExternal)->externalToCustom($corpid, $external_userid);
            $followTag                    = [];
            foreach ($extUser['follow_user'] as $followUser) {
                if (isset($followUser['userid'])) {
                    $open_userid_info = (new ContactService())->get_external_contact_batchget_user_list_by_data($corpid, [$followUser['userid']]);
                    $followUser['userid'] = !empty($open_userid_info) ? $open_userid_info[0] : $followUser['userid'];
                }
                if ($userid != $followUser['userid'])    continue;
                $FollowTagModel->query()->where(['corpid' => $corpid, 'external_userid' => $external_userid, 'follow_userid' => $userid])->delete();
                foreach ($followUser['tags'] as $value) {
                    // 组合数据
                    $followTag[]        = [
                        'corpid' => $corpid,
                        'external_userid' => $external_userid,
                        'follow_userid' => $followUser['userid'],
                        'tag_name' => $value['tag_name'],
                        'tag_id' => $value['tag_id'],
                        'type' => $value['type'],
                        'insert_time' => time(),
                        'update_time' => time(),
                    ];
                }
                $followUser                = [
                    'corpid' => $corpid,
                    'external_userid' => $external_userid,
                    'follow_userid' => $followUser['userid'],
                    'remark' => $followUser['remark'],
                    'description' => $followUser['description'],
                    'add_way' => $followUser['add_way'],
                    'oper_userid' => array_key_exists('oper_userid', $followUser) ? $followUser['oper_userid'] : '',
                    'state' => (isset($followUser['state']) ? $followUser['state'] : (isset($followUser['State']) ? $followUser['State'] : '')),
                    'status' => 0,
                    'createtime' => $followUser['createtime'],
                    'remark_corp_name' => (isset($followUser['remark_corp_name']) ? $followUser['remark_corp_name'] : ''),
                    'remark_mobiles' => implode(',', $followUser['remark_mobiles']),
                    'update_time' => time(),
                ];
                // 修改数据
                $oldData = $FollowModel->query()->where(['corpid' => $corpid, 'external_userid' => $external_userid, 'follow_userid' => $userid])->value('id');
                // 新增时间
                if (!$oldData)            $followUser['insert_time'] = time();
                // 写入数据
                $followUser['id'] = $oldData ? $FollowModel->query()->where([['id', '=', $oldData]])->update($followUser) : $FollowModel->query()->insertGetId($followUser);
            }
            // 标签处理
            if ($followTag) {
                $FollowTagModel->query()->insert($followTag);
                //同步标签到SASS平台
                $TagLogService->add_user_tag_sync_info($corpid, $external_userid);
            }
            //删除任务记录
            $this->Records->delete();
            // 成功处理...
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', 'UpdateUserTagJobs任务队列处理失败', ['data' => $this->message_data, 'error' => $e->getMessage()]);
        }
    }


    /**
     * 渠道活码打标签业务功能
     * @author    唐远望
     * @version   1.0
     * @date      2025-11-12
     */
    public function channel_qrcode_tag($work, $userid, $external_userid, $state)
    {
        $qrcodeExplode = explode('&', $state);
        if (isset($qrcodeExplode[1]) && $qrcodeExplode[0] == 't1') {
            $qrcodeId = $qrcodeExplode[1];
            //通过qrcodeId 获取tags
            $tags = (new Qrcode())->query()->where(['id' => $qrcodeId])->value('tags');
            //tags不为空才操作打标签
            if (empty($tags)) {
                $this->Records->delete();
                return true;
            }
            //过滤已经被删除的标签
            $TagModel = new TagModel();
            $tags_array = $TagModel->query()->whereIn('tag_id', explode(',', $tags))->pluck('tag_id')->toarray();
            if (empty($tags_array)) {
                Log::info('job_error', 'UpdateUserTagJobs自动打标签错误,配置标签在标签库没有找到', ['data' => $tags]);
                $this->Records->delete();
                return true;
            }
            $insertData['userid'] = $userid; // 成员ID
            $insertData['external_userid'] = $external_userid; // 外部联系人的userid
            $insertData['add_tag'] = $tags_array; // 要打的标签
            // 数据结果
            $result = $work->external_contact->markTags($insertData);
            if (!$result || $result['errcode']) {
                Log::info('job_error', 'UpdateUserTagJobs自动打标签错误：', ['data' => $insertData, 'error' => $result]);
                return true;
            }
        }
    }


    public function failed(\Throwable $exception)
    {
        Log::info('job_error', 'UpdateUserTagJobs任务队列彻底失败', ['data' => $this->message_data, 'error' => $exception->getMessage()]);
        // 失败处理...
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
