<?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\Facades\Servers\Wechat\OpenWork;
use App\Models\OpenWork\Contactway\QrcodeWelcome as QrcodeWelcomeModel;
use App\Models\OpenWork\External\Welcome as WelcomeModel;

/**
 * 渠道活码欢迎语任务队列
 * @author    唐远望
 * @version   1.0
 * @date      2025-11-12
 * 
 */
class QrcodeWelcomeJobs 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 . '_QrcodeWelcomeJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);

            $userid = $this->message_data['userid'];
            $welcomeCode = $this->message_data['WelcomeCode'];
            $state = $this->message_data['state'];
            $external_userid = $this->message_data['external_userid'];

            $QrcodeWelcomeModel = new QrcodeWelcomeModel();
            $WelcomeModel = new WelcomeModel();
            $work  = OpenWork::getWork($corpId);
            $extUser   = $work->external_contact->get($external_userid);
            if (!$extUser || $extUser['errcode']) {
                Log::info('job_error', 'QrcodeWelcomeJobs获取外部人详情错误：', ['data' => $external_userid, 'error' => $extUser]);
                $this->Records->delete();
                return true;
            }
            $external_user_name = $extUser['external_contact']['name'];
            $msg                        = [];
            $isQrcodeWelcomeFlag         = 0; // 是否有渠道活码欢迎语
            if (!empty($state)) {
                //解析state
                $qrcodeExplode = explode('&', $state); //t1&qrcodeId
                if (isset($qrcodeExplode[1]) && $qrcodeExplode[0] == 't1') {
                    $qrcodeId = $qrcodeExplode[1];
                    //通过qrcodeId 获取tags
                    $qrcodeWelcome = $QrcodeWelcomeModel->getOneByQrcodeId($corpId, $qrcodeId, '');
                    //如果存在欢迎语
                    if ($qrcodeWelcome) {
                        if ($qrcodeWelcome['content'] || $qrcodeWelcome['attachments']) {
                            // 欢迎语文本消息
                            if ($qrcodeWelcome['content'])             $msg['text'] = ['content' => $qrcodeWelcome['content']];
                            //组合附件消息
                            if ($qrcodeWelcome['attachments'])        $msg['attachments'] = $qrcodeWelcome['attachments'];
                            $isQrcodeWelcomeFlag = 1;
                        }
                    }
                }
            }
            //如果没有渠道活码的欢迎语则使用成员对应的欢迎语
            if ($isQrcodeWelcomeFlag == 0) {
                // 获取成员对应的欢迎语
                $userWelcome = $WelcomeModel->getOneByUserId($corpId, $userid, '');
                // 如果存在欢迎语
                if ($userWelcome) {
                    // 内容和图片不能同时为空
                    if ($userWelcome['content'] || $userWelcome['attachments']) {
                        // 欢迎语文本消息
                        if ($userWelcome['content'])             $msg['text'] = ['content' => $userWelcome['content']];
                        // 组合附件
                        if ($userWelcome['attachments'])         $msg['attachments'] = $userWelcome['attachments'];
                    }
                }
            }
            // 发送欢迎语
            if ($msg) {
                if (!empty($msg['text']['content'])) $msg['text']['content'] = str_ireplace('{客户昵称}', $external_user_name, $msg['text']['content']);
                $msgResult =  $work->external_contact_message->sendWelcome($welcomeCode, $msg);
                if ($msgResult['errcode']) {
                    Log::info('job_error', 'QrcodeWelcomeJobs任务队列处理失败', ['data' => $this->message_data, 'error' => $msgResult]);
                }
            }
            //删除任务记录
            $this->Records->delete();
            // 成功处理...
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', 'QrcodeWelcomeJobs任务队列处理失败', ['data' => $this->message_data, 'error' => $e->getMessage()]);
        }
    }



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